I’m trying to output the text value from a list node. Any idea why it’s not working. How do i tell how many childNodes are in the ul element?
function test(){
var x = document.getElementById("test");
alert(x.firstChild.nodeValue);
}
<ul id="test">
<li>
Alec
</li>
<li>
Daniel
</li>
<li>
William
</li>
<li>
Stephen
</li>
</ul>
Ah yes, the old “phantom node” talk.
run a
var nodeArray = x.childNodes;
Then see what is contained in your nodeArray (you have Firebug right?). If you see something like this:
\
, <li>, \
, <li>, \
Then you have pesky phantom nodes. The way around this is to make yourself an array that filters out the phantom nodes. So something like this
var i;
var liArray = [];
for (i=0; i < nodeArray.length; i++) {
if (nodeArray[i].nodeType == 1) { //nodeType == 1 means it's an element node (not a text node like "\
" would be)
liArray.push(nodeArray[i]);
}
}
then liArray should only contain your <li> elements. Good luck!