【问题标题】:How can I select an element which does not contain a certain child element?如何选择不包含某个子元素的元素?
【发布时间】:2012-04-27 10:27:53
【问题描述】:
<div class="test">
 <div class="example"></div>
</div>

<div class="test">
</div>

我如何才能将 jQuery 应用于类为 test 的元素,前提是它不包含类为 example 的子元素?

【问题讨论】:

标签: javascript jquery


【解决方案1】:
$('.test:not(:has(.example))')

-或-

$('.test').not(':has(.example)')

【讨论】:

    【解决方案2】:

    可能

    $('.test').filter(function() { return !$(this).children('.example').length; });
    

    这会过滤掉任何具有匹配.example 的子元素的元素。如果您想根据后代(不仅仅是孩子)进行过滤,您可以将 .find 替换为 .children

    【讨论】:

      【解决方案3】:
      $(':not(.test:has(.example))').css('color', 'red');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
      

      http://jsfiddle.net/9fkz7y1g/

      【讨论】:

      • 您的 JSFiddle 不包含您答案中的代码。
      【解决方案4】:

      jQuerycontains():

      jQuery.contains(document.documentElement, document.body); // true
      jQuery.contains(document.body, document.documentElement); // false
      

      【讨论】:

        【解决方案5】:

        这个问题似乎已经为 filter 函数准备好了,您可以在其中找到所有 .test 对象,然后在过滤时只保留其中没有 .example 的对象:

        $(".test").filter(function() {
            return($(this).find(".example").length == 0);
        });
        

        【讨论】:

          【解决方案6】:

          您可以将children 方法与“.example”一起使用并测试它是否为空

          【讨论】:

            【解决方案7】:
             $('.test').each(function() {
                if(!$(this).children().hasClass("example")){
                   //your code
                }
            }); 
            

            也许是这样的?我没有测试过这个...

            【讨论】:

              【解决方案8】:
              if (!$('#yourDiv').children().hasClass("className")) {
                  //i.e. yourDivID' has no any children whose class name =>'className'
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-06-15
                • 1970-01-01
                • 2014-05-17
                • 2014-08-31
                相关资源
                最近更新 更多