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

494
Visualizações
How to bring it back the eventListener after replaceChild in vanila javascript?

Well I wanna ask something about replaceChild in here and I was got trouble when I used that function, so the problem is when I have some function addEventListener on my button, when I was replace the old button to new element then bring back again, my event listener on my old button doesn't work like before, any suggest to keep my event listener work on my button when my button was replace? Oh ya in bellow I will give you all the link of example of my problem, you can access to understand more about my problem, thanks before have a nice day!

I'll put my code in bellow :

const button = document.querySelectorAll('.button');

button.forEach(function (element) {
    element.addEventListener('click', function () {
    const buttonClass = element.classList;
    
    if (buttonClass.contains('custom')) {
        const buttons = document.querySelector('.buttons');
      const testElement = document.createElement('p');
        testElement.innerHTML = "I'm Paragraph"
      
      buttons.replaceChild(testElement, buttons.lastElementChild);
    } else {
        const buttons = document.querySelector('.buttons');
      const customElement = document.createElement('button');
        customElement.className = "button custom"
        customElement.innerHTML = "5"
        
      buttons.replaceChild(customElement, buttons.lastElementChild);
    }
  });
});

document.querySelector('.custom').addEventListener('click', function () {
    console.log('you touched me!')
});
<div class="buttons">
  <button class="button">1</button>
  <button class="button">2</button>
  <button class="button">3</button>
  <button class="button">4</button>
  <button class="button custom">5</button>
</div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use event delegation: listen for the click on a container element. These click events bubble up, so even when a new button generates the event, it will bubble up to the container you are listening on.

You can do the same for the buttons that don't get replaced, so your code remains together, and you don't have to iterate the buttons.

Adapted code:

const buttons = document.querySelector('.buttons');

// Listen on a container element -- could even be body
// Grab the event argument
document.querySelector('.buttons').addEventListener('click', function (e) {
    // Then check whether the source of the event was our button
    const buttonClass = e.target.classList;
    if (buttonClass.contains("custom")) {
        console.log('you touched me!');
        const testElement = document.createElement('p');
        testElement.innerHTML = "I'm Paragraph";
        buttons.replaceChild(testElement, buttons.lastElementChild);
    } else {
        const customElement = document.createElement('button');
        customElement.className = "button custom";
        customElement.innerHTML = "5";
        buttons.replaceChild(customElement, buttons.lastElementChild);
    }
});
<div class="buttons">
  <button class="button">1</button>
  <button class="button">2</button>
  <button class="button">3</button>
  <button class="button">4</button>
  <button class="button custom">5</button>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

When you bring back the element, that means you are adding the new element to the HTML DOM. In this case, again, you have to bind that element with the eventListener. I would suggest use classes to bind the event and delegate or removeEventListner and rebind it whenever you bring back the element to the DOM.

about 4 years ago · Juan Pablo Isaza 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