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

495
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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