gpt4 book ai didi

javascript - JS中根据父id抓取div数组

转载 作者:行者123 更新时间:2023-12-03 02:44:07 24 4
gpt4 key购买 nike

我有一个包含 3 列的页面。每列中都有几个具有相同类名的 div,如下所示。

<div id="column1">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

<div id="column2">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

<div id="column3">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

我希望能够抓取每列下的每个子 div 并将它们存储到 JS 中的 3 个单独的数组中。所以在伪代码中

var children1 = all children of #column1 with the class .child,
children 2 = all children of #column2 with the class .child,
children 2 = all children of #column2 with the class .child;

我需要能够根据 .child div 所在的列为其应用背景颜色。我将如何执行此操作?

最佳答案

document.querySelectorAll()它返回 NodeList对象和 Array.from() .

示例

var children1 = document.querySelectorAll('#column1 > .child'),
children2 = document.querySelectorAll('#column2 > .child'),
children3 = document.querySelectorAll('#column3 > .child'),
content1 = Array.from(children1, child => child.textContent);

console.log(content1);
<div id="column1">
<div class="child">Column 1a</div>
<div class="child">Column 1b</div>
<div class="child">Column 1c</div>
</div>

<div id="column2">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

<div id="column3">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

关于javascript - JS中根据父id抓取div数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48178695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com