Reputation: 686
I have a grid made in html like so
<div class="grid-container" id="grid-container">
<div class="grid-row">
<div class="grid-cell red"><p class="label">R</p></div>
<div class="grid-cell"></div>
<div class="grid-cell blue"><p class="label">B</p></div>
</div>
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell white"><p class="label">W</p></div>
<div class="grid-cell"></div>
</div>
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell blue"><p class="label">B</p></div>
<div class="grid-cell blue"><p class="label">B</p></div>
</div>
</div>
I want to be able to make JavaScript updates to each cell individually. For this I tried to write a script that gets all the child nodes of the grid and then again get the child nodes of each row. However when I test the output the three rows return fine but the children of them return as 7 objects instead of 3. I'm very confused...
function myFunction() {
var c = document.getElementById("grid-container").childNodes;
var b;
var txt = "";
for (var i = 0; i < c.length; i++) {
txt = txt + "Row: " + c[i].nodeName + "<br>";
b = c[i].childNodes;
for (var j = 0; j < b.length; j++) {
txt = txt + "Cell: " + b[i].nodeName + " Value: " + b[i].className + "<br>";
}
}
document.getElementById("demo").innerHTML = txt;}
Here is the output it gives me:
Upvotes: 0
Views: 1115
Reputation: 686
For the sake of writing an answer credit to Loilo, simply use children
instead of childNodes
Upvotes: 1