繁体   English   中英

在JavaScript中获取节点的所有子节点

[英]Get all children of a node in javascript

我想让所有<p>孩子。

HTML:

<p id="p">nodlist is an <i> ordered <b>collection of node</b> objects that are </i>children of the current element.<font color="blue"> If the element</font> has no children, then contains no node.</p>

JavaScript的:

var childrens = [];

function getchilds(node){       

    if(node.nodeType == 1){
    var childnodes = node.childNodes;

        for(i=0; i<childnodes.length; i++){

            var child = childnodes[i];
            if(child.nodeType == 1)
            getchilds(child);

       }
    }else
    childrens.push(node);
}

var childnodes = document.getElementById('p').childNodes;       
for(i=0; i<childnodes.length; i++){

    getchilds(childnodes[i]);

}

但是childrens[]是:

0:nodlist是一个

1:订购

2:节点集合

3:是

4:没有子节点,则不包含节点。

children of the current element以及If the element已丢失,并且当我将<a>元素(如<a href="url"> link </a>p标签时,脚本将陷入无限循环。

看起来您正在循环中使用全局变量i ,这意味着从内部函数调用返回时您将丢失元素。 更改为

for(var i=0; i<childnodes.length; i++){

在两个循环中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM