htmldomhtml-tablechildrentree-nodes

HTML table DOM creates wrong number of child elements


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?


Solution

  • 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