我希望得到<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
元素时,脚本陷入了无限循环。
答案 0 :(得分:1)
您似乎正在使用全局变量i
来表示循环,这意味着您在从内部函数调用返回时会错过元素。将其更改为
for(var i=0; i<childnodes.length; i++){
在两个循环中。