Languages

JavaScript - simulate mouse click on multiple elements?

0 points
Asked by:
Jacob
532

Can you tell me how to simulate mouse click on multiple div elements using JavaScript?

Let's say I have three div elements:

<div id="my-element1" onclick="console.log('1')"></div>
<div id="my-element2" onclick="console.log('2')"></div>
<div id="my-element3" onclick="console.log('3')"></div>

I want a for loop that loops through all my-elements and fires their onclick event.

1 answer
0 points
Answered by:
Jacob
532

You can use querySelectorAll() to get handles to all the elements and then inside a for loop execute click() method on each element.

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-element1" onclick="console.log('1')"></div>
  <div id="my-element2" onclick="console.log('2')"></div>
  <div id="my-element3" onclick="console.log('3')"></div>
  <script>

    var elements = document.querySelectorAll(`div[id^="my-element"]`);

    for (var i = 0; i < elements.length; ++i) {
        elements[i].click();
    }

  </script>
</body>
</html>

 

References

  1. HTMLElement.click() - Web APIs | MDN
  2. Document.querySelectorAll() - Web APIs | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join