How to run getElementsByTagName only on child elements of an element?

I am having problems with the correct operation of the selector.

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 am trying to select tags divthat are children ui-controlgroup-controls, which means throwing what's inside the form.

Here is what I am trying:

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

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

Question :
How to choose the elements correctly if I do not want to use jQuery?

+5
source share
4 answers

One way to do this is to iterate over the 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/

( ) querySelectorAll :

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

, querySelectorAll:

var divs = el.children[0].querySelectorAll("div");

, slice NodeList (, IE, , IE < 9):

var slice = Function.call.bind(Array.prototype.slice);

var divs = slice(el.children[0].children).filter(function(node) { 
               return node.tagName === "DIV"
           });

, :

var nodes = el.children[0].children;
var divs = [];

for (var l = nodes.length, node; node = nodes[--l];) {
  if (node.tagName === "DIV")
    divs.push(node);
}
+2

:

el.querySelectorAll(".ui-controlgroup-controls > div")

, ".ui-controlgroup-controls", .

, .children div.

var divs = [];

for (var i = 0, len = el.children.length; i < len; i++) {
    if (el.children[i].classname === "ui-controlgroup-controls") {
        for (var j = 0, lenj = el.children[i].children.length; j <, lenj; j++) {
            if (el.children[i].children[j].nodeName === "DIV") {
                divs.push(el.children[i].children[j])
            }
        }
    }
}

, ui-controlgroup-controls, children[0].

var divs = [];

for (var j = 0, lenj = el.children[0].children.length; j <, lenj; j++) 
    if (el.children[0].children[j].nodeName === "DIV") 
        divs.push(el.children[o].children[j])
+1
<your-element>.querySelectorAll(":scope > div");

:scope - , . IE, shim.

0
source

All Articles