简体   繁体   中英

How can you use one block of code to target all the classes on a website? (no jquery)

I've been working on a game as part of some class work and have run into an issue. The issue is the code only effect one button. I'm using the following on a two '.restart' buttons to reload the browser....

//Reload Page
document.querySelector('.restart').addEventListener('click', function () {
    location.reload();
});

One restart button is on the top(like a header). The other is in a Modal. The Modal shows up first in the HTML. I'm 99.9% this is why the second one gets skipped. I've tried using document.querySelectorAll.... However I get a Uncaught TypeError: document.querySelectorAll(...).addEventListener is not a function and neither works. How can I use one snippet to control all the same classes with Javascript? Below is a code pen of the game...

https://codepen.io/AB3D/pen/xJWMpd

This happens because querySelectorAll() returns an array of elements.
The solution would be to iterate through these elements and attach the event to each one of them.

 <button class="restart">Button 1</button> <button class="restart">Button 2</button> <button class="restart">Button 3</button> <script> var elements = document.querySelectorAll(".restart"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener("click", function() { location.reload(); }); } </script>

Since you're using a class name as a selector , you can also use getElementsByClassName("restart") as an alternative , this method also returns an array of elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM