Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

82
Vistas
add an event listener on an element I've created in javascript

I'm trying to add event listener to multiples element I created before in my script.

I've tried that method first :

document.body.addEventListener('click', function (event) {
    if (event.target.class === "deleteCommentButton"){
        deleteComment();
    }
})

But it doesn't seems to work, so I'm now trying to do with this method, which seems to be better :

const addEventTobutton = () => {
    document.querySelectorAll('.deleteCommentButton').addEventListener('click', deleteComment);
    document.querySelectorAll('.modifyCommentButton').addEventListener('click', modifyComment);
}

does someone have an explanation for me to understand why my code isn't working ?

thanks

almost 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

in your first code you are adding an event listener to the document body, rather than your element. it is not the ideal way to create an event listener, as it is quite inefficient. instead add the listener to the element you want to detect the event on.

const newElement = document.createElement( 'div' );
newElement.addEventListener( 'click', () => {} );

on top of that, to detect an element's class, you should use classList.contains()

if ( newElement.classList.contains( 'deleteCommentButton' ) ) {
almost 4 years ago · Santiago Trujillo Denunciar

0

QuerySelectorAll is an array and therefore, I couldn't add event on it. Need to loop with something like :

  arrayDeleteButton.forEach(deleteBtn => {
        deleteBtn.addEventListener('click', deleteComment)
    });
    arrayModifyButton.forEach(modifyBtn => {
        modifyBtn.addEventListener('click', modifyComment);
    }) 

is this a better solutions than what you guys proposed or should I go your way ?

almost 4 years ago · Santiago Trujillo Denunciar

0

The answer is easy you should use className instead of class for the first approach to work .

That will give all the classes of an element

for that you can use

 event.target.className.contains("deleteCommentButton")
almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda