Attempting to access DOM nodes, getting wrong nodeValues and lengths
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?
There are text nodes (with nothing visible in them) between the <li>
nodes. 5+4 = 9.
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).
精彩评论