Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all class's with getElementsByClassName and click

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

like image 852
Max Port Avatar asked Sep 13 '13 11:09

Max Port


People also ask

How do you get the class element on click?

To find the class of clicked element, we use this. className property. The className property is used to set or return the value of an element's class attribute. Using this property, the user can change the class of an element to the desired class.

How do you select all classes in HTML?

class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.

What is getElementsByClassName () used for?

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.

How do you select multiple classes in JavaScript?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.


2 Answers

[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

like image 128
Harry Avatar answered Sep 20 '22 10:09

Harry


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()
}
like image 24
Nishad K Ahamed Avatar answered Sep 22 '22 10:09

Nishad K Ahamed