Skip to content

Can not read properties of addEventListener in Javascript [closed]

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’)”.

const btnsOpenModal = document.querySelectorAll('.show-modal');

for (var i = 0; i = btnsOpenModal.length; i++)
  btnsOpenModal[i].addEventListener("click", function() {
    console.log("Button clicked");
  });
<button class="show-modal">Show modal 1</button>
<button class="show-modal">Show modal 2</button>
<button class="show-modal">Show modal 3</button>

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.