Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
(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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!