gpt4 book ai didi

javascript - 在不知道匹配元素嵌套位置的情况下选择匹配元素,但不选择那些匹配元素的子元素

转载 作者:太空宇宙 更新时间:2023-11-04 16:00:42 25 4
gpt4 key购买 nike

请建议一个更好的标题,让其他用户更容易找到这个问题。

我正在尝试选择父元素的子元素,但该子元素可能是某个子元素的子元素,对嵌套子元素的数量没有限制。我想选择那个 child ,但如果在许多嵌套的 child 中有那个 child 的 child ,我不想选择那个 child 。例如:

<div class="section">
<div> <!--First nested child (Take this and repeat as many times as you want within the parent 'section' class, structure of nested children changing each time.)-->
<div> <!--Second nested child (Can have potentially infinite sub-nests like first, second, etc.)-->
<div class="block"> <!--Select this -->
Select
<div>
<div class="block"> <!--DONT select this -->
Don't select
<div class="section">
<div> <!--More unknown nestings to an assumed infinite degree-->
<div class="block"> <!--Select this-->
Select
<div>
<div class="block">Don't select</div> <!--DONT select this -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div>
<div>
<div class="block"> <!--Select this -->
Select
<div>
<div class="block"> <!--DONT select this -->
Don't select
<div class="section">
<div> <!--More unknown nestings to an assumed infinite degree-->
<div class="block"> <!--Select this-->
Select
<div>
<div class="block">Don't select</div> <!--DONT select this -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

这看起来非常糟糕,但我们的想法是我们只想选择任何 child 中的第一次出现,然后不再出现。

我显然更喜欢 CSS 来做这个选择,但是如果需要的话我们可以使用 jQuery 选择器。我不确定在 CSS 中是否可行。

一个 fiddle 给你玩:https://jsfiddle.net/78b3c6xh/1/

There are three solutions to this question. I've selected the pure CSS one from Arman P. as the answer because that was what the question asked for in preference and it is the fastest and simplest of the solutions.

The second best is from Susanne Peng due to simplicity and minimal use of jQuery. Not sure about efficiencies, but it works.

The third is ibrahim mahrir who was the first to solve, and utilizes a custom javascript function with dependency on jQuery.

Recommend using the CSS solution if possible in this situation. Working fiddle with solution is in the comments on that answer.

最佳答案

我不认为这仅用 CSS 是可能的。

使用 jQuery 的解决方案:

$('.section').each(function() {
$(this).find('.block').first().css('color', 'blue');
});

在这里 fiddle :https://jsfiddle.net/78b3c6xh/2/

如果在一个 .section 下可以找到多个子 .block,您可以采用如下方法:

$('.block').each(function() {
var $closest = $(this).parent().closest('.section, .block');
if ($closest.hasClass('section')) $(this).css('color', 'blue');
});

在这里 fiddle :https://jsfiddle.net/78b3c6xh/5/

关于javascript - 在不知道匹配元素嵌套位置的情况下选择匹配元素,但不选择那些匹配元素的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41904552/

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