Tbi45
Tbi45

Reputation: 607

Get all elements with the same class

I know that this:

document.getElementsByClassName('class-1')[0]. 

selects the first <div> that has the specify class.

I guess using a for() will get through the whole array of <div>.

Can somebody explain how to create that array ?

I will prefer plain Js.

Upvotes: 7

Views: 35536

Answers (1)

VisioN
VisioN

Reputation: 145428

Method getElementsByClassName() returns a set of DOM elements that have a certain class name. Here is a canonical example of how to use the returned list of nodes:

var elements = document.getElementsByClassName("class-1");
for (var i = 0, len = elements.length; i < len; i++) {
    // elements[i].style ...
}

Upvotes: 24

Related Questions