views:

16

answers:

2

I have the following HTML :

<ul id="nav">
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
    <li><a href="#">Four</a></li>
</ul>

On attempting to walk the element,

1 nav.childNodes.length is 9, What are the nine nodes?

2 nav.childNodes[0].nodeType is 3, but .nodeValue is empty.




EDIT:

It works fine after doing:

<ul id="nav"><li><a href="#">One</a></li><li><a href="#">Two</a></li><li><a href="#">Three</a></li><li><a href="#">Four</a></li></ul>

Why is white-space being counted as nodes?

+3  A: 

There are text nodes (with nothing visible in them) between the <li> nodes. 5+4 = 9.

Pointy
Is white-space normally considered as a node?
Babiker
Well it annoys me too but that's what HTML/XML parsers seem to do.
Pointy
+1, What is the solution for this? Its misery to write a web page in a single line.
Babiker
I agree. It's things like this that make me appreciate Javascript frameworks that can deal with issues like this. As @Peter Ajtai says, the behavior is not consistent across different browsers anyway. It's something I'm happy to turn over to the designers (and testers!) of a utility framework like Prototype or jQuery. Of course your situation is your own, and you can make your own decisions on things like that. (In other words, I don't want this to be a "Just use jQuery!" response; I'm just giving my opinion.)
Pointy
+1  A: 

Beware what you state is not true in IE. In IE your code shows 4 child nodes. This is because IE does not count whitespace as nodes, but Mozilla, Chrome, and Safari do.

Like Pointy said, whitespaces are nodes in all but IE, so whitespace after ul, and the 4 li's is 5 nodes of whitespace + 4 nodes of li = 9 nodes.

If you only want the LI nodes:

document.getElementById("nav").getElementsByTagName("li").length

The above shows 4 as the answer. And it works the same in all browsers.

If you must use all child nodes, simply ignore the type 3 nodes (text and thus whitespace) and concentrate on the type 1 nodes (element nodes).

Peter Ajtai