Beginner in JavaScript has question

<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“utf-8”>
<title>DOMinating JavaScript</title>
</head>
<body>
<h1 id=“pageTitle”>
DOMinating JavaScript
</h1>
<p>
If you need some help with your JavaScript, you might like
to read articles from:
</p>
<ul id=“test”>
<li><a href=“http://www.danwebb.net/” rel=“external”>Dan Webb</a></li>
<li><a href=“http://www.quirksmode.org/” rel=“external”>PPK</a></li>
<li><a href=“http://adactio.com/” rel=“external”>Jeremy Keith</a></li>
</ul>
<script type=“text/javascript” src=“example.js”></script>
</body>
</html>

If I try this code the alert I get in the browser is object Text
var test=document.getElementById(“test”);
var testChild=test.childNodes[0];
alert(testChild);

If I try this code the alert I get in the browser is object HTMLLIELEMENT
var test=document.getElementById(“test”);
var testChild=test.childNodes[1];
alert(testChild);

If I try this code the alert I get in the browser is object Text
var test=document.getElementById(“test”);
var testChild=test.childNodes[2];
alert(testChild);

If I try this code I get no alert
var test=document.getElementById(“test”);
var testChild=test.childNodes[childNodes.length-1];
alert(testChild);

I was expecting all of the alerts to come back with LI but I do not know why that was not the result for all of them.

Help please.

Thank you.

Ronny

childNodes is a little deceiving when you first come across it. You’d think it would just get child elements.

What’s easy to overlook is that childNodes actually gets child text nodes as well. (Because newlines and spaces between tags are considered text nodes).

If you want to just get the child elements (i.e. the <li>s) try using the .children property instead :slight_smile:

I tried the following code with no results

var test=document.getElementById(“test”);
var testChild=test.children[children.length-1];
alert(testChild);

Ah, that’s because when you try to get the children.length, children isn’t defined, you would have to use test.children.length

What browser are you working in? If you’re in Firefox, I would highly recommend installing Firebug. If you’re in Chrome or Opera, they have built-in developer tools you can use. ([URL=“http://www.youtube.com/watch?v=nOEw9iiopwI”]Paul Irish did a video a little while ago with some tips for the [URL=“http://www.chromium.org/devtools”]Chrome dev tools that might be worth watching.)

Thanks a lot for your help after some tries I came up with this and I got the result I wanted.

var list = document.getElementById(“test”);
var listItems = list.children;
for (i=0; i<listItems.length;i++)
{
alert(listItems[i].nodeName)
}