gpt4 book ai didi

javascript - 如何根据 child 在 DOM 树中的位置选择 child

转载 作者:搜寻专家 更新时间:2023-10-31 22:55:55 25 4
gpt4 key购买 nike

假设我有这样的html

<div class='parent'>
<div class='dad'>
<div class='teen'>
<div class='baby'>
</div>
</div>
</div>
<div class='dad'>
</div>
</div>

如何根据 div 与父级的距离来定位 div?例如.baby 前面有 3 个父对象,.teen 前面有 2 个父对象。有什么办法吗?因为我最终想做的是针对每个第二个 child ()。所以在这种情况下,我想选择 .dad.baby。但我不想选择固定数量,我希望它无限选择 DOM 树中的每个 2nd child()。

最佳答案

var $result = $("div").filter(function() {
return $(this).parents("div").length % 2 != 0; // if the number of div parents is not a pair number
});

$result.each(function() {
$(this).css("background", "red");
});
div {
border: 1px solid black;
background: white;
padding: 10px;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<div>
<div>
</div>
<div>
<div>
</div>
</div>
</div>
</div>
<div>
</div>
</div>

注意:如果你想包括所有的 parent ,那么使用这个:

return $(this).parents().length % 2 != 0;

关于javascript - 如何根据 child 在 DOM 树中的位置选择 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42359114/

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