I want to get all children of <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]);
}
but childrens[]
is:
0 : nodlist is an
1 : ordered
2 : collection of node
3 : objects that are
4 : has no children, then contains no node.
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.
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. Change it to
for(var i=0; i<childnodes.length; i++){
in both loops.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.