HTML table DOM creates wrong number of child elements

371 Views Asked by At

I have a table in my code which I am using as a look-up table, by grabbing some values from <td> based on the id of the <tr>.

<table>
<tr id="nas">
<td>1.34</td>
<td>0.67</td>
<td>1</td>
<td>1.25</td>
</tr>
</table>

When I have my table typed-in as shown above and when I do: document.getElementById("nas").childNodes.length the result is 9, while clearly I have only 4 child elements of the element <tr id="nas">. Some of the child elements are real <td>s with values, some are just empty elements.I am really confused with this one.

However if I type-in the table all in one line, I get the correct number of children.

<table>
<tr id="nas"><td>1.34</td><td>0.67</td><td>1</td><td>1.25</td></tr>
</table>

Why do you think this is happening?

4

There are 4 best solutions below

1
On BEST ANSWER

childNodes includes ALL childNodes, include text nodes (i.e., the white-space in between your cells). Try something like this:

var children = document.getElementById('nas').childNodes,
    count = 0,
    len = children.length;

for (var i = 0; i < len; i++) {
    // make sure it's type ELEMENT_NODE
    if (children[i].nodeType === 1) { count++ }
}

alert(count); // 4
0
On
childNodes
0 <TextNode textContent="\n">   
1 td
2 <TextNode textContent="\n">
3 td
4 <TextNode textContent="\n">
5 td        
6 <TextNode textContent="\n">
7 td
8 <TextNode textContent="\n">

I dont exactly know who makes the text nodes, the browser or javascript parser, but thats what javascript is seeing.

0
On

Because the newline between the tags is counted as text, and gets transformed into a text node in the DOM.

0
On

There is a good article explaining the problem here: https://developer.mozilla.org/en/whitespace_in_the_dom