申请变更为包含使用jQuery一定的子元素的所有父元素

问题描述 投票:1回答:2

我试图做同样的事情,但this question我的父元素没有一个id。它有通过类。基本上我有同一个类的多个元素和一些有子元素。如果类example的成员包含子,应用一些CSS改变。这是可能的,我会怎么做呢?

例如:

<div class="example">
    <div id="findMe"></Div>
</div>
<div class="example">
  <!-- This div would not be found -->
</div>

我的猜测是:

let parents = $(".example");
for (var i=0; i < parents.length; i++) {
    if (parents[i].find('#test').length) {
        parents[i].css("prop", "value")
    }
}

parents[i].find is not a function

javascript jquery css
2个回答
1
投票

所以,你不应该有一个文件在同一个ID的多个实例。但是,在你的榜样,你是八九不离十。但是,如果你已经使用jQuery它会让你的生活更容易一点。

<div class="example">
    <div class="findMe"></Div>
</div>
<div class="example">
  <!-- This div would not be found -->
</div>

jQuery的:

(我使用$来表示一个jQuery集合,你不会需要它)

这个jQuery集合(在这种情况下,通过查找创建)总是有一个长度。所以,你需要测试它是否是空的。此外$。每()本质上是通过收集循环。

let $parents = $('.example');
$parents.each(
    function(){
      var $el = $(this);
      if($el.find('.findMe').length !=0){
         $el.css('background', 'red');
      }
    }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:100px;" class="example">
    <div class="findMe">Hello, World!</Div>
</div>
<div style="height:100px;border: solid 1px #000" class="example">
  <!-- This div would not be found -->

</div>

1
投票

作为Heretic Monkey在评论中说上面,你可以使用has从jQuery来轻松地做到这一点。

$(".example").has(".findMe").css("background-color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:100px;" class="example">
    <div class="findMe">Hello, World!</Div>
</div>
<div style="height:100px;border: solid 1px #000" class="example">
  <!-- This div would not be found -->
</div>
© www.soinside.com 2019 - 2024. All rights reserved.