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

142
Vistas
(Javascript) Re-Initialize Loop after adding some elements via "document.createElement("div")"

I am currently struggling with a problem, that's pretty hard to describe for me, but I try my best.

I built a loop which looks like this:

for (var j = 0; j < button_remove_ingredient.length; j++) {
 button_remove_ingredient[j].addEventListener("click", () => {
  button_remove_ingredient = document.querySelectorAll(".remove_ingredient");
  document.querySelectorAll(".ingredient_list")[j].remove();
  })
}

The problem is that the loop is loading after the moment the DOM is created and in this time button_remove_ingredient has the length of 1 because there is only one button in the HTML.

There is another function, which creates clones of that button after pressing another button.

So in this case, it's possible to have several button_remove_ingredient but only if the user really interacts with the interface.

Now, only the first button fires the eventListener, the other ones not and when I console.log(j) inside the eventlistener, it will always show me 1.

I wanted to try that with a foreach loop but it didn't work either.

I would be very glad if somebody did understand my problem and has a good solution for that.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I used an eventListener checking the classList of the event target in order to remove it.

Please check snippet below:

document.body.addEventListener('click',  () => {
  if(this.event.target.classList.contains("remove_ingredient")){
    this.event.target.remove()
  }
  
  }, true); 
  function addButton(){
    document.getElementById("container").innerHTML += '<button class="remove_ingredient">New Button</button>';
    
  }
<div id="container">
<button class="remove_ingredient">Button 1</button>
<button class="remove_ingredient">Button 2</button>
<button class="remove_ingredient">Button 3</button>
</div>
<button onclick="addButton()">Add new button</button>

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