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!
CodePudding user response:
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.
CodePudding user response:
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
}