简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM