I have the following code:
<ul id="meganFox">
<li>Frank</li>
<li>Jeff</li>
<li>Bob</li>
</ul>
<div id="debug"></div>
<script language="javascript">
var nodes = document.getElementById('meganFox').childNodes;
var el = document.getElementById('debug');
for( var i = 0; i < nodes.length; i++ ){
el.innerHTML += i +' - '+ nodes[i] +'<br />';
}
alert( nodes.length );
</script>
Firefox alert: 7
0 – [object Text]1 – [object HTMLLIElement]
2 – [object Text]
3 – [object HTMLLIElement]
4 – [object Text]
5 – [object HTMLLIElement]
6 – [object Text]
IE alert: 3
0 – [object]
1 – [object]
2 – [object]
Why is it 7? What is object text versus just object?
My end goal is to capture the key event and navigate through it with the up and down arrows. I got it working properly in IE, but it isn’t working in FF because of this issue.
W3 compliant browsers consider whitespace between elements to be part of the DOM (text nodes).
Older versions of IE don’t. That’s why you get 3 in IE, vs 7 elsewhere.
The
[object]output is just apparently what IE’stoString()of element nodes gives.If you don’t want any text nodes, then do this in your
forloop…This will eliminate all text nodes (not just empty ones). To preserve non-empty nodes, you can do this…