Answers for "how to add event listener to all buttons"

-2

how to add event listener to all buttons

<button class="btn">
    Button1
</button>
<button class="btn">
    Button2
</button>
<button class="btn">
    Button3
</button>
<button class="btn">
    Button4
</button> //HTML

//JavaScript
var buttons = document.querySelectorAll(".btn").length;

for (var i = 0; i < buttons ; i++) {
    document.querySelectorAll(".btn")[i].addEventListener("click", function() {
        alert("Button Clicked");
    });
}
Posted by: Guest on August-20-2020

Code answers related to "how to add event listener to all buttons"

Browse Popular Code Answers by Language