2

What is the easiest way to get list of all [tag] nodes that are direct children of the given node, without using query?

AlexTR
  • 772
  • 8
  • 14
  • 1
    Can you please elaborate "`without using query`"? jQuery? Or something else? – Teemu Apr 17 '14 at 17:35
  • @Teemu - Assuming OP means just plain vanilla JS. – j08691 Apr 17 '14 at 17:36
  • @Teemu I mean neither use side libraries as jQuery nor querySelector() function – AlexTR Apr 17 '14 at 17:38
  • Maybe you are looking for something like this? https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName – wongcode Apr 17 '14 at 17:42
  • @AlexTR: Why wouldn't you use `document.querySelector[All]`? Its support is better than the alternative `document.getElementsByTagName`, and it tends to outperform the `getElementsBy*` DOM queries anyway – Elias Van Ootegem Jul 09 '14 at 06:53
  • @EliasVanOotegem this question was a part of my learning process. I cant just always use the simpliest method, because its simple. Instead, I like to know what alernative options are there for me and test their relative efficiency. – AlexTR Jul 09 '14 at 16:44
  • @AlexTR: `document.querySelector` and `querySelectorAll` are part of the DOM API since IE8 first was released. It's not because it's simple to use, that you should use it. It's because it's the official, standard DOM call that is best supported that you ought to use it. – Elias Van Ootegem Jul 10 '14 at 07:27

3 Answers3

4

With an iteration, you can check the tag name of the element like that :

var child = yourElement.children;
var childrensSpan = [];

for(var i = 0; i < child.length; i++){
    if(child[i].tagName === "SPAN") childrensSpan.push(child[i])
}

console.log(childrensSpan);

Fiddle : http://jsfiddle.net/Paesk/

Of course, yourElement is your parent element and "SPAN" is the tag you are searching for.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
2

In modern browsers...

var divs = [].filter.call(node.children, function(el) {
    return el.nodeName === "DIV";
});

The Array.prototype.filter method can be patched in legacy browsers.


If you're going to do this frequently for different types of elements, you may want to shorten it by making a function that creates the filter callback.

function byTag(name) {
    name = name.toUpperCase();
    return function(el) {
        return el.nodeName === name;
    }
}

And then do this:

var divs = [].filter.call(node.children, byTag("div"));
cookie monster
  • 10,671
  • 4
  • 31
  • 45
0

Based on the answers here I made two functions and wrapped them into HTMLElement.prototype which resulted in ability to use divChildren = node.childrenByTag("div");

Later I made a little benchmark comparsions between two solutions that were offered here, querySelector(), getElementsByTagName(), regexp and XPath

If anyone is interested you can find it here(functions+benchmarks): http://jsfiddle.net/2CPwL/

AlexTR
  • 772
  • 8
  • 14