How to run getElementsByTagName on children of an element only?
Solution 1
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')
Solution 2
For the browser that supports querySelectorAll:
var divs = el.children[0].querySelectorAll("div");
For the browsers that supports the usage of slice on NodeList (e.g. not IE, at least not IE < 9):
var slice = Function.call.bind(Array.prototype.slice);
var divs = slice(el.children[0].children).filter(function(node) {
return node.tagName === "DIV"
});
For the browsers that doesn't support neither:
var nodes = el.children[0].children;
var divs = [];
for (var l = nodes.length, node; node = nodes[--l];) {
if (node.tagName === "DIV")
divs.push(node);
}
Solution 3
<your-element>.querySelectorAll(":scope > div");
:scope
is a pseudo-class representing the parent element. No support in IE, but there is a shim.
frequent
Updated on June 17, 2022Comments
-
frequent almost 2 years
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 ofui-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?