How to run getElementsByTagName on children of an element only?

frequent picture frequent · Apr 1, 2013 · Viewed 13.8k times · Source

I'm having trouble getting a selector to work properly.

I have this HTML:

<div.wrapper>
    <div.ui-controlgroup-controls>
        <form>
            <div.ui-btn></div>
        </form>
        <div.ui-btn></div>
        <div.ui-btn></div>
        <div.ui-btn></div>
        <div.ui-btn></div>
    </div>
</div>

and I'm trying to select the div tags, which are children of ui-controlgroup-controls - which means excluding whats inside the form.

This is what I'm trying:

// el is my div.wrapper element
el.children[0].getElementsByTagName("div");

However this does not work, because the div inside the form ends up in the selection.

Question:
How can I select the elements correctly when I don't want to use jQuery?

Answer

Asad Saeeduddin picture Asad Saeeduddin · Apr 1, 2013

One way to do this is to iterate over your resulting node list and check the parent:

var nodes = el.children[0].getElementsByTagName("div");
nodes = Array.prototype.slice.call(nodes);
nodes = nodes.filter(function(v, i){
    return v.parentElement === el.children[0]; 
});

Here is a demonstration of this approach: http://jsfiddle.net/WLhY2/

A simpler (albeit less efficient) approach is to use querySelectorAll to retrieve the relevant nodes using a selector expression:

var divs = document.querySelectorAll('div.ui-controlgroup-controls > div')