[英]How do you loop through an unknown amount of children and children of children in javascript
我正在尝试遍历看起来像这样的 html...
<div>
<span>
...
</span>
<span>
...
</span>
<span>
...
</span>
<span>
...
</span>
<div>
<header>
...
</header>
<div>
...
</div>
<div>
...
</div>
...
</div>
<div>
<header>
...
</header>
<div>
...
</div>
<div>
...
</div>
...
</div>
<div>
<header>
...
</header>
<div>
...
</div>
<div>
...
</div>
...
</div>
...
</div>
我需要获取 div 子项的每个 div 中的数据,忽略所有 header 元素和 span 元素。 每个 div 子元素中有未知数量的 div 子元素和未知数量的 div。 有没有办法可以遍历这个,我已经尝试了一个小时,但我离做这件事还差得远。
这是我尝试过的,我正在使用 selenium。
let i = 4
while(driver.findElement(By.xpath(`//*[@id="football"]/div/div/div/div[${i}]`))){
let j = 1
while(driver.findElement(By.xpath(`//*[@id="football"]/div/div/div/div[${i}]/div/div/div[${j}]`))){
console.log(i, j)
j++
}
i++
}
这只是记录 4, 1 然后 4, 2 然后 4,3 等等......
这是递归“算法”的一个非常简单和幼稚的示例,用于获取给定 DOM 节点的所有后代。
const findAllChildren = (root) => root.children.length > 0? [root, [...root.children].flatMap(findAllChildren)].flat(): root; console.log( findAllChildren(document.body) );
<p>Hello</p> <div>Hello <div>World</div> </div> <div>Hello <div>World <div>Hello <div>World</div> </div> </div> </div>
我希望您可以使用它来制作自己的更好的实现。
如果您只想要底部的 div 元素(上例中的[<div>World</div>, <div>World</div>]
),您可以执行以下操作:
const findAllChildren = (root) => root.children.length > 0? [...root.children].flatMap(findAllChildren): root; console.log( [...document.querySelectorAll('body > div')].flatMap(findAllChildren) );
<p>Hello</p> <div>Hello <div>World</div> </div> <div>Hello <div>World <div>Hello <div>World</div> </div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.