.addeventlistener() is not a function

Asked

Viewed 4,105 times

3

I’m building a script for modals, but an unexpected error happened, the console says:

Uncaught Typeerror: loginBtn.addeventlistener is not a Function`", "at modaisGeral (index.html:233)" and "at index.html:235",

How can I correct?

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();

2 answers

5


document.querySelectorAll returns a list of elements and not an element as such.

Soon, loginBtn is a array and cannot add a eventListener in a array.

If you want to add the same eventListener for all elements of this array, will need to loop 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++xdU5avIH0Ro9bC6ZNUCWkg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 3</button>
<button id="4" class="login-modal-open">Botão 4</button>
<a id="5" class="login-modal-open" href="#">Link 5</button>

  • Obg, thanks for the readiness :D

2

Complementing the @jbueno response /a/199222/13469

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 element found that has the class informed.

To add the event to all elements corresponding to document.querySelectorAll, you could do so:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.