var res = document.querySelectorAll("#a,#b,#c,#d")
res[0].innerHTML = "apple"
res[1].innerHTML = "bananna"
res[2].innerHTML = "orange"
res[3].innerHTML = "lemon"
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>
<p id="d"></p>
This is running fine, but I want to be able to use something like this:
var res = document.querySelectorAll("#a,#b,#c,#d")[i].innerHTML =
{"apple","bananna","orange","lemon"}
CodePudding user response:
Use a simple loop. I will highly recommend you to go over some simple JS tutorial so that you enjoy coding
const elements = document.querySelectorAll("#a,#b,#c,#d")
for (let i = 0; i < elements.length; i ) {
elements[i].innerHTML = `text${i 1}`
}
CodePudding user response:
This should work for you by using template literal
var res = document.querySelectorAll("#a,#b,#c,#d")
for(let i in res){
res[i].innerHTML = `test${i}`
}
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>
<p id="d"></p>
CodePudding user response:
As far as data is concerned, you need at minimum a way to pick a target, a piece of content for that target, and a way to tie the target and content together. One way this might be done is:
const data = [
['#a', 'apple'],
['#b', 'banana'],
['#c', 'orange'],
['#d', 'lemon'],
];
Now that you have all the necessary data and its associations, making use of it could look like:
data.forEach(([target, content]) => {
document.querySelector(target)?.innerHTML = content;
});
Reference:
