简体   繁体   English

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

[英]Get all children of a node in javascript

I want to get all children of <p> . 我想让所有<p>孩子。

HTML: 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: 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]);

}

but childrens[] is: 但是childrens[]是:

0 : nodlist is an 0:nodlist是一个

1 : ordered 1:订购

2 : collection of node 2:节点集合

3 : objects that are 3:是

4 : has no children, then contains no node. 4:没有子节点,则不包含节点。

children of the current element and If the element have missed, and when I add <a> element like <a href="url"> link </a> to p tag, the script gets stuck in an infinite loop. children of the current element以及If the element已丢失,并且当我将<a>元素(如<a href="url"> link </a>p标签时,脚本将陷入无限循环。

Looks like you're using a global variable i for the loops which means you're going to miss elements when returning from an inner function call. 看起来您正在循环中使用全局变量i ,这意味着从内部函数调用返回时您将丢失元素。 Change it to 更改为

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

in both loops. 在两个循环中。

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

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