Arun P Johny
Arun P Johny

Reputation: 388316

How to iterate through all the sub elements of an element

If I have a html dom as shown below, with out using any library (like jQuery) how can I iterate through all the sub elements of any given element. I need to check whether some custom attributes are set on those elements.

<div id="testme">
    <span><a></a></span>
    <div>
        <ul>
            <li><a></a></li>
        </ul>
    </div>
</div>

Upvotes: 1

Views: 4844

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

It is pretty easy using the html dom + javascript.

var printhere = document.getElementById("printhere");

function stepthrough(el, prefix){
    prefix = prefix || "";
    if(el ){
        //Ignore the text nodes
        if(!el.nodeName || !(/#text/i.test(el.nodeName))){
            printhere.innerHTML += "<br />" + prefix + el.tagName;
            if(el.firstChild){
                stepthrough(el.firstChild, prefix + "--");
            }
        }

        if(el.nextSibling){
            stepthrough(el.nextSibling, prefix)
        }
    }
}

stepthrough(document.getElementById("testme"));

You can customize the printhere.innerHTML += "<br />" + prefix + el.tagName; part of the code to fit it into any anything.

You can find a working example in this fiddle.

This is an recursive function which goes through all the children and subchildren of the given node

Upvotes: 4

jcolebrand
jcolebrand

Reputation: 16025

Keeping my answer simple for the benefit of getting to the meat of the matter. Try either of these, which would you like?

//direct descendent nodes
var children = document.getElementById('id').childNodes;

// or

//all nodes below the top node?
var children = document.getElementById('id').getElementsByTagName('*');

Upvotes: 4

Related Questions