.addEventListener () is not a function

3

I'm setting up a script for modal, however an unexpected error occurred, the console says:

  Uncaught TypeError: loginBtn.addEventListener is not a function '"," at modalsGeneral (index.html: 233) "and" at index.html: 235 ",

How can I fix it?

function modaisGeral(){
    var principalModal = document.querySelector("modais");//Recebe um elemento
    var loginBtn = document.querySelectorAll(".login-modal-open");//Recebe um array de elementos
    var loginModal = document.getElementById("login-modal");//Recebe o modal de login

    loginBtn.addEventListener("click", function(){});

}modaisGeral();
    
asked by anonymous 19.04.2017 / 14:27

2 answers

5

document.querySelectorAll returns a < strong> element list and not an element itself.

So, loginBtn is an array and it is not possible to add a eventListener to an array .

If you want to add the same eventListener to all elements of this array , you will need to loop through the elements and add it.

var elementos = document.querySelectorAll('.login-modal-open');

for(var el of elementos){
  el.addEventListener('click', function(){
    console.log(this.id);
  });
}
<a id="1" class="login-modal-open" href="#">Link 1</a>
<img id="2" class="login-modal-open"src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAABHFJREFUWIW9l1tsVGUQgL+Z0xbabqk2aitRmgC7pVz6YniQB0sjl0dCFJ+M8RLfjIaAwRDx9AAPGJR6S0yIiQHji1ESX7y03u+J8RIQLC1iiEApUG13txey3RkfdrcpbWmX0vA/nX9m/pnvn/PPmf8IN2G4IwOtS5Yowcog0H8qX+j8paAruRkA/724eEGpBt0A5tk3gTEAvRkANc+dHjDjHAAmK8fr5hRgMEqsToWJ9z2snz9RJ/gf+ccmd2TOAZJhw4Ojxo8oD6SlLJpkIHIsH7F6eG/jojkH8HnyJeqXAExk+0DYsOYqvfrxwnPGRsdew5wBVO/s7AuMJ/JOVdUP9exvqizoS7JaeAUIsmrOAQBiUfdHOAfz06WVgyP7CroKkifM8NzMbzwD9vJd5VPJh7xkG2Z/A4jwVCpK3A8gUc+QKn8B+LhKmBXAULh40WB6/tlUFG+dCFIbnUg78mhht2a8/e++xdU5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
<button id="3" class="login-modal-open">Botão 3</button>
<button id="4" class="login-modal-open">Botão 4</button>
<a id="5" class="login-modal-open" href="#">Link 5</button>
    
19.04.2017 / 14:45
2

Complementing @jbueno's response link

You would have to choose which index of this array you would add the event, for example:

loginBtn[0].addEventListener("click", function(){});

So you would add the event to the first found element that has the class informed.

To add the event to all elements that correspond to document.querySelectorAll , you could do this:

for (var i = 0; i < loginBtn.length; i++)
  loginBtn[i].addEventListener("click", function() {alert('Funcionou!')});
    
19.04.2017 / 14:53