简体   繁体   English

如何遍历新创建的元素?

[英]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.假设我每次向父 div 提交表单时都会附加一个新的 div。 How would I loop through all of those newly created div elements?我将如何遍历所有这些新创建的 div 元素? 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?我如何循环遍历每个 newDiv 元素? 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.我试过使用 for of 循环循环但说它不可迭代。 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.如果您尝试遍历parentDiv ,那么是的,它不是可迭代的 object。但是,一种解决方案可能只是将您创建的新 div 附加到列表中,然后像往常一样遍历列表。

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您可以使用getElementsByClassName()方法,这将为您提供一个类似于 object 的数组,您可以像这样通过索引迭代和访问每个元素

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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