Imagine having 3 div elements and 3 different sets of arrays. The goal is to assign the values from each array into corresponding divs. How can this be achieved?
Take a look at my sample divs below:
<div id='001'><div id="nr001"><div id="clr001"></div></div></div>
<div id='002'><div id="nr002"><div id="clr002"></div></div></div>
<div id='003'><div id="nr003"><div id="clr003"></div></div></div>
Now, I have 3 sets of arrays obtained through JSON.parse() as shown below:
["001", "002", "003"],["8", "9", "20"], [ "brown", "black", "yellow"]
The Desired Outcome: The objective is to populate the divs with the respective values from the arrays like this:
<div id='001'>8<div id="nr001"><div id="clr001">brown</div></div></div>
<div id='002'>9<div id="nr002"><div id="clr002">black</div></div></div>
<div id='003'>20<div id="nr003"><div id="clr003">yellow</div></div></div>
Here's what I've attempted so far:
var str = xmlHttp.responseText;
var res = JSON.parse(str);
var set1 = res[0], set2 = res[1], set3 = res[3];
for (var i = 0; i < set1.length; i++) {
var div1 = document.getElementById("nr"+set1[i]);
var div2 = document.getElementById("clr"+set1[i]);
if (div1) {
div1.innerHTML = set2[i];
}
if (div2) {
div2.innerHTML = set3[i];
}
}
Only div2 seems to be populated, not div1. Perhaps more lines of script or a new approach are needed.
AFTER IMPLEMENTING THE SOLUTION:
I want to express my gratitude to everyone who provided a solution. It turns out that I failed to mention I used setTimeout() to recall the function every 15 seconds. So, other answers suggested appending the element? Does the result get appended to the previous one when another call finishes?
In the end, by assigning spans instead of using divs for both, the issue was resolved. Now, I am getting the desired output. Thank you to all contributors!