Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

immediate children of a list

Tags:

javascript

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.

like image 357
racky Avatar asked Jul 01 '10 17:07

racky


3 Answers

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/

like image 85
Bill Barry Avatar answered Nov 06 '22 07:11

Bill Barry


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]);
    }
}
like image 4
Anurag Avatar answered Nov 06 '22 08:11

Anurag


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);
    }
}
like image 2
xavierm02 Avatar answered Nov 06 '22 08:11

xavierm02