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

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

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