Reputation: 23
I am a beginner at javascript. I want to use javascript to browse all the elements in the dom and print its name, I wrote the following:
function getNumber(parent){
var entiredoc = parent;
var docnodes = entiredoc.childNodes;
return docnodes.length;
}
function browAllDom(parent){
if(parent!=null){
for(i = 0; i < getNumber(parent); i++){
alert(parent.nodeName);
return browAllDom(parent.childNodes[i]);
}
}
}
when I debug, it browses the leaf in the tree dom and exits. I think it has to browse all in the for loop.
Where's the problem? And how can I you fix it?
Upvotes: 1
Views: 46
Reputation: 18923
The following code will run only a single time:
for(i = 0; i < getNumber(parent); i++){
(parent.nodeName);
return browAllDom(parent.childNodes[i]);
}
This code will run only once since you are returning from the for loop.
Instead you should write the return outside of the for loop.
Have a look at this answer. You will have a better understanding.
Upvotes: 1