Max
Max

Reputation: 73

How can I select elements with a class using getElementsByClassName and click them?

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

Upvotes: 5

Views: 61601

Answers (5)

Sasidharan
Sasidharan

Reputation: 3750

$(".node closed").filter(function() {
    return $(this).click();
});

Upvotes: -3

Voonic
Voonic

Reputation: 4785

document.getElementsByClassName has some issues in IE

use jquery

window.onload=function(){

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

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

});

}

Upvotes: -2

Harry
Harry

Reputation: 89780

[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

Upvotes: 21

Nishad K Ahamed
Nishad K Ahamed

Reputation: 1394

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()
}

Upvotes: 3

Ganesh Pandhere
Ganesh Pandhere

Reputation: 1652

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

Upvotes: -3

Related Questions