0

I grab all elements by a specific class name like below:

var button = document.getElementsByClassName('submit')

I would like to iterate through what is retrieved and click on all buttons with that class name. I tried something like

for(var i in button){
  i.click()}

But that does not seem to work. How would I go about clicking each button that is retrieved?

aj soprano
  • 151
  • 1
  • 6
  • 1
    What do you mean with *does not seem to work*; what is supposed to happen? Please create a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) for us to work with. – Emiel Zuurbier Mar 05 '22 at 20:39
  • [this](https://stackoverflow.com/questions/15843581/how-to-correctly-iterate-through-getelementsbyclassname) may help you. – llo Mar 05 '22 at 20:44

1 Answers1

0

There are lots of ways you can do it, but you can do it like this:

const btns = document.querySelectorAll('.anyButtonClass');

btns.forEach(function(btn){
  // when ever this code runs, it will automatically click all your buttons
  btn.click();
  console.log(btn.innerHTML);

  // btn.addEventListener('click', function(e){
    // console.log(btn.textContent);
  // })
})
<div class="btn-container">
  <button class="anyButtonClass">Click Me 1</button>
  <button class="anyButtonClass">Click Me 2</button>
  <button class="anyButtonClass">Click Me 3</button>
</div>
VebDav
  • 152
  • 6
  • this doesnt quite accomplish what I want. the buttons are clicked one at a time. I would want all the buttons to be clicked at the same time by iterating over each button – aj soprano Mar 06 '22 at 20:07
  • Okay, so you want all your buttons clicked, whenever the code is triggered. See above. – VebDav Mar 06 '22 at 20:59