I am making a simple web app with three buttons (“Show Modal 1”, “Show Modal 2 and Show Modal 3) I want that at the moment of click the buttons a addEventListener will print in console “Button Clicked” every time the buttons are clicked, But for some reason it gives me the follow error: “Uncaught TypeError: Cannot read properties of undefined (reading ‘addEventListener’)”.
JavaScript
x
6
1
const btnsOpenModal = document.querySelectorAll('.show-modal');
2
3
for (var i = 0; i = btnsOpenModal.length; i++)
4
btnsOpenModal[i].addEventListener("click", function() {
5
console.log("Button clicked");
6
});
JavaScript
1
3
1
<button class="show-modal">Show modal 1</button>
2
<button class="show-modal">Show modal 2</button>
3
<button class="show-modal">Show modal 3</button>
Advertisement
Answer
As the comment already points out, the syntax is wrong. You are making a comparison in your for loop ending condition. However you are using an assignment operator. Read more about the differences in assignment and comparison here.