当我们不知道括号的深度时,我正在寻找通用解决方案。然而,例子是这样的:
<div id="parent">
<div id="parent_child">
<div id="parent_child_child">
<div id="parent_child_child_child">
</div>
</div>
</div>
</div>
如何在普通 JavaScript 中循环访问这样的结构?
最佳答案
如果jQuery
是一个选项,您可以使用后代选择器
来查找所有子节点(任意深度),然后使用.each
迭代它们。
$("#parent div").each(function(){
//your code goes here
});
纯 JavaScript 解决方案是。
Array.from(document.querySelectorAll("#parent div")).forEach(function(itm){
console.log(itm); //itm represents the individual element.
});
-
document.querySelectorAll()
将根据以下内容抓取元素 提供的选择器。 -
Array.from
会将节点列表转换为原生数组。 -
forEach
在迭代数组时会很方便。
关于javascript - 如何循环嵌套子结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534122/