Este es el código que me pregunto. ¿Hay alguna forma en que pueda interpolar la variable 'i' para ir tras el objeto del cuerpo? Esto haría que en el primer ciclo fuera body0, luego body1, y así sucesivamente. Intenté hacer body + i.innerHTML pero da un error. ¿Alguien sabe cómo haría para hacer esto?
JS:
let url = 'https://poetrydb.org/random,linecount/1;10/title,author,lines.json' const button = document.getElementById("button") const title = document.getElementById("title") const author = document.getElementById("author") const body = document.getElementById("body") const fullBody = document.getElementById("fullbody") async function requestPoem(url) { let response = await fetch(url); let data = response.json() return data } button.onclick = async () => { let data = await requestPoem(url) title.innerHTML = data[0].title author.innerHTML = data[0].author for (let i = 0; i < 10; i++) { body.innerHTML = data[i].lines } }HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script defer src="scripts/main.js"></script> <title>poem request</title> </head> <body> <div id="fullbody"> <h2 id="title"></p> <h3 id="author"></h3> <p id="body1"></p> <p id="body2"></p> <p id="body3"></p> <p id="body4"></p> <p id="body5"></p> <p id="body6"></p> <p id="body7"></p> <p id="body8"></p> <p id="body9"></p> <p id="body10"></p> </div> <button id="button">request poem</button> </body> </html>Bueno, una forma cruda podría verse así:
const data = [ 'Poem line 1', 'Poem line 2', 'Poem line 3' ]; for (let i = 0; i < data.length; i++) { document.getElementById(`body${i+1}`).innerHTML = data[i]; } <section> <p id="body1"></p> <p id="body2"></p> <p id="body3"></p> </section>pero si comparte más del código que tiene (incluido el marcado), podría haber una solución más elegante.
EDITAR Solución actualizada basada en la información proporcionada por OP
let url = 'https://poetrydb.org/random,linecount/1;10/title,author,lines.json' const button = document.getElementById("button") const title = document.getElementById("title") const author = document.getElementById("author") const body = document.getElementById("body") const fullBody = document.getElementById("fullbody") async function requestPoem(url) { let response = await fetch(url); let data = response.json() return data } button.onclick = async () => { let data = await requestPoem(url) title.innerHTML = data[0].title author.innerHTML = data[0].author fullBody.innerHTML = data[0].lines.reduce((val, cur) => { return val + `<p>${cur}</p>`; }, ''); } <h2 id="title"></p> <h3 id="author"></h3> <div id="fullbody"></div> <button id="button">request poem</button>