tags:

views:

47

answers:

3

Hey, A quick question.. what's the JAVASCRIPT statement to get the immediate children of a LIST? I tried:

document.getElementById(id).getElementsByTagName('li');

which gives me all of the child nodes.

+1  A: 

Node.childNodes or Element.children

var listItems = [];

var children = elem.childNodes;
for(var i = 0; i < children.length; i++) {
    if(children[i].nodeName == "LI") {
        listItems.push(children[i]);
    }
}
Anurag
Note that `childNodes` contains all nodes and just elements.
Gumbo
thanks @Gumbo - I will clarify that point in the answer later. Shouldn't matter for small lists as we're testing by `nodeName`, but may be an inefficient for larger lists.
Anurag
Better use `children[i].nodeType === Node.ELEMENT_NODE` to make sure it’s really an element node.
Gumbo
`LI` shouldn't be returned as the nodeName for any other type of node. Since `nodeName` is defined on `Node`, it should be available as a property for all nodes, including text, and others.
Anurag
+1  A: 

loop through:

document.getElementById(id).children

and get the ones that are li elements (I think they should all be according to spec)


I think document.querySelectorAll('#id>li') if it is supported should work as well. See: http://www.w3.org/TR/selectors-api/

Bill Barry
Hmm, looks like children isn't part of a DOM standard, just part of gecko and perhaps other rendering engines... childNodes is probably the better answer even if you have to check each element of the list.
Bill Barry
so is that document.getElementById(id).childNodes; that would get me only the immediate children?
racky
yes, note that if you have firebug installed, you can see both of these lists in the watch window right on this site with a watch like `document.getElementsByTagName("ul")[0]`
Bill Barry
A: 

The same code faster & better.

var listItems = [];
var children = element.childNodes;
for(var i = 0, l=children.length; i<l; ++i) {
    var child = children[i];
    if(child.nodeType === 1 && child.tagName === "LI") {
        listItems.push(child);
    }
}
xavierm02