Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

84
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda