5

I cant seem to click all of the elements.

document.getElementsByClassName('node closed')[0].click();

This works but will only click on the first element. I need this to click all of the elements with class 'node closed'.

Thanks

5 Answers 5

21

[0] means only the first element of the node list returned by getElementsByClassName.

You have to do getElementsByClassName and iterate through all the matched elements like shown below:

var el = document.getElementsByClassName('node closed');
for (var i=0;i<el.length; i++) {
    el[i].click();
}

Working Demo

Sign up to request clarification or add additional context in comments.

4 Comments

I tried this but i just get the error: TypeError: Object #<NodeList> has no method 'click'
Yes, sorry I was about to edit my post. The click method wouldnt work on a node list. you have to iterate through all elements returned from the node list.
This works but doesnt seem to activate them all. <span class="node closed" onclick="doExpandCollapse(this)"></span> is there a way of activating that onclick event?
@MaxPort Check this fiddle. I have modified it to suit your structure. The onclick function is coded to print the id of the element to the console log.
3

iterate the result in a loop and assign click to each elements:

var list=document.getElementsByClassName('node closed')
for(var i=0;i<list.length;i++){
list[i].click()
}

Comments

-2

document.getElementsByClassName has some issues in IE

use jquery

window.onload=function(){

$(.yourclass).each(function(){

 $(this).trigger('click');

});

}

Comments

-3

just remove [0] and it will access all matched elements as [0] points to first element only.

3 Comments

Maybe in jQuery, but not in vanilla JS.
In that case, question was supposed be more descriptive. And solution provided is as per the normal logic applied in javascript for indexing elements.
jQuery objects have that "normal logic", but not HTMLCollections returned by getElementsByClassName().
-3
$(".node closed").filter(function() {
    return $(this).click();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.