'Interpolating variable with object name [closed]
This is the code I am wondering about. Is there anyway I could interpolate the 'i' variable to go after the body object. This would make it so on the first loop it was body0, then body1, and so on. I tried to do body + i.innerHTML but it gives out an error. Does anyone know how I would go about doing this?
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>
Solution 1:[1]
Well, a crude way could look something like this:
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>
but if you share more of the code you have (including the markup) there might be a more elegant solution.
EDIT Updated solution based on provided info by 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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |