user971637
user971637

Reputation:

traverse through elements returned by getElementsByClassName

I'm finding all elements for a class name with getElementsByClassName like this:

var elements = document.getElementsByClassName('myclass');

and I want to travers all elements including children of children, all elements.

what I'm doing now is this:

for(var i=0; i< elements.length; i++) elements[i].children[0];

but this is not good because it will not traverse all elements including children of children. And I don't know the parent children tree.

How traverse all elements of parent element including children of children.

Upvotes: 1

Views: 907

Answers (4)

herau
herau

Reputation: 1516

generic way :

var recursive = function (element) {
// some stuff with element
console.log(element);
// check if children
var children = element.children;
if (children) {
    for(var i=0; i< children.length; i++) { 
        // apply recursion on each child
        recursive(children[i]);
    }
}
}

var elements = document.getElementsByClassName('postcell');

for(var i=0; i< elements.length; i++) { 
 recursive(elements[i]);
}

Upvotes: 2

Paul S.
Paul S.

Reputation: 66304

Using getElementsByTagName('*') you can arrange your code like this so you have a nested loop and a variable elm inside it which points at the current node to let you do work on it.

var elements = document.getElementsByClassName('myclass'),
    i, j, nodes, elm;

for (i = 0; i < elements.length; ++i) {
    nodes = Array.prototype.slice.call(elements[i].getElementsByTagName('*'));
    nodes.unshift(elements[i]);
    for (j = 0; j < nodes.length; ++j) {
        elm = nodes[j];
        // work with elm
    }
}

If you wanted to just return an Array of all the Elements, you could concat the Array I called nodes instead of the second for

Upvotes: 0

ArmaGeddON
ArmaGeddON

Reputation: 339

You can try this:

var elements = document.body.getElementsByTagName("*");
var eleMyClass = new Array();
var j=0;
for(i=0; i<elements.length; i++){
    if(elements[i].className=="myclass"){
    eleMyClass[j]=elements[i];
    j++;
    }
}

Now the Array eleMyClass contains the list of the elements with class Name myclass

Upvotes: 1

Quentin
Quentin

Reputation: 943207

element.getElementsByTagName('*') will give give you all the descendant elements of an element.

Alternatively, you can use children recursively.

Upvotes: 1

Related Questions