[英]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.