开发者

immediate children of a list

开发者 https://www.devze.com 2023-01-05 22:21 出处:网络
A quick question.. what\'s the JAVASCRIPT statement to get the immediate children of a LIST? I tried:

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 t开发者_如何学JAVAhe child nodes.


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/


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]);
    }
}


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号