Click on all elements of a class

Asked by At

I'm creating a script (pure JS) to click on all elements of a certain class.

function f() {
  var elements = document.getElementsByClassName("myclass")
  elements.click()
}
//ignore the CSS
button {
  border: none;
  background-color: white;
}
<button onclick="alert('k')" class="myclass">The function f should click on me!</button>
<button onclick="f()">Click on me for the function f</button>

I created this script that should click on all elements with a class of myclass. Why does it not do that? Thanks!

1 Answers

0
Artem Mirchenko On

Because getElementsByClassName always returns an array of elements.

You need to loop through them.

Example:

function f(){
var elements = document.getElementsByClassName("myclass").forEach(el => el.click())
}