2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user414071
  • 23
  • 2

4 Answers4

2
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.

Pheonix
  • 6,049
  • 6
  • 30
  • 48
1

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

herkulano
  • 548
  • 3
  • 10
0

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

Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
0

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
jmar777
  • 38,796
  • 11
  • 66
  • 64
  • 1
    A note to those reading: this is a quick and easy alternative to the `ElementNode.children` collection, which has spotty browser support. –  Sep 07 '11 at 20:40