1

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?

2
  • 1
    return browAllDom(parent.childNodes[i]); ... means that the loop will run at most one time ... return returns out of enclosing function Commented Sep 27, 2017 at 6:43
  • 1
    An easy way would be to use parent.getElementsByTagName('*'), that returns a flattened object of all elements in parent. Commented Sep 27, 2017 at 6:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.