简体   繁体   中英

How to loop through a newly created element?

Let's say I am appending a new div every time I submit a form to a parent div. How would I loop through all of those newly created div elements? For example:

const parentDiv = document.querySelector("div")

form.addEventListener("submit", function formSubmit(e) {
    e.preventDefault()
    let newDiv = document.createElement("div")
    newDiv.classList.add("new-Div")
    parentDiv.append(newDiv) 
})

How could I loop through every newDiv element? I am trying something similar on a project I am working on and can't seem to find a solution. I have tried looping through using a for of loop but saying it is not iterable. Any help would be great!

If you tried looping through the parentDiv then yes it is not an iterable object. However, one solution could be just appending the new divs you create to a list and looping through the list like normal.

You can use getElementsByClassName() method, that will give you an array like object that you can iterate and access each element by their index like this

const newDiv = document.getElementsByClassName("new-Div");

for (let i = 0; i < newDiv.length; i++) {
    console.log(newDiv[i]);
  //do whatever
}

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