Getting text value from childNodes (ref Simply Javascript)

Hi All,

I’m going through Simply Javascript and I’m having trouble getting the value of a childNode (is it possible?). What I am doing is out of the scope of what it was currently teaching me (I think) – getting the actual value of the node.


<ul id="baldwins">
  <li>Alec</li>
  <li>Daniel</li>
  <li>William</li>
  <li>Stephen</li>
</ul>

<script type="text/javascript">
var baldwins = document.getElementById("baldwins");
var william = baldwins.childNodes[2];

document.write(william.nodeValue); // FireBug DOM says it's "\
      "
document.write(william) // page displays [object Text]
document.write(william.nodeName) // page displays #text
</script>

Can someone help point me in the right direction? I just want it to display William.

Thanks

Inbetween the different elements are whitespace, which most browsers also allow you to reference, IE being the exception.

So in some browsers the 5th element is the third element

[list][]0 - whitespace
[
]1 - 1st li
[]2 - whitespace
[
]3 - 2nd li
[]4 - whitespace
[
]5 - 3rd li
[*]6 - whitespace
[/list]

Whereas in other browsers, the 2nd element is what you’re after.

[list][]0 - 1st li
[
]1 - 2nd li
[*]2 - 3rd li
[/list]

A safer way to get the element you’re after is to use getElementsByTagName instead

The other problem that you’ve facing is that the LI element doesn’t actually have a value in and of itself. You’ll be needing the childNode of the LI element, that being the text node itself.


var baldwins = document.getElementById("baldwins");
var william = baldwins.getElementsByTagName('LI')[2];

document.write(william.firstChild.nodeValue); // William

Thanks Paul, this works great!

I was going through it more, and just wondered if there was a way to easily go through the list and their siblings using firstChild, lastChild, nextSibling, previousSibling?

When you’re dealing with html code you’re going to run into the whitespace by using those techniques.

You can alternatively use something like the following to process the contents of all the LI elements.


var els = baldwins.getElementsByTagName('LI');
for (var i = 0; i < els; i++) {
    document.write(els.firstChild.nodeValue);
}

There is also the possibility to use the DOM 2 Traversal [URL=“http://developer.mozilla.org/en/docs/DOM:treeWalker”]TreeWalker.

It is very powerful and allows you choose what kind of elements you want returned, run a filter on each element etc.

Maybe an overkill for this example, but it this would give you what you want:

var ul = document.getElementsByTagName("ul")[0];
var treeWalker = document.createTreeWalker(ul, NodeFilter.SHOW_ELEMENT, null, false);

while (treeWalker.nextNode()) {
	alert(treeWalker.currentNode.textContent);
}

What is the catch with this? It’s not implemented in IE…