简体   繁体   English

jquery选择没有嵌套在孩子身上的孩子

[英]jquery selecting children not nested in a child

I have some problems with a jQuery selector. 我有一个jQuery选择器的问题。

Let's say I have the following html where (...) stands for an undefined number of html tags. 假设我有以下html,其中(...)代表未定义数量的html标签。

(...)
<div class="container">
  (...)
    <div class="subContainer">
      (...)
        <div class="container">
          (...)
            <div class="subContainer"/>
          (...)
        </div>
       (...)
     </div>
   (...)
</div>
(...)

Let say that I have a javascript variable called container that points to the first div (with class container). 假设我有一个名为container的javascript变量指向第一个div(带有类容器)。 I want a jquery that selects the first subcontainer but not the nested one. 我想要一个jquery来选择第一个子容器而不是嵌套的子容器。 If I use $(".subContainer", container); 如果我使用$(".subContainer", container); I'll get both of them. 我会得到他们两个。

I've tried using 我试过用了

$(".subContainer:not(.container .subContainer)", container);

but this returns an empty set. 但这会返回一个空集。 Any solution? 有解决方案吗

Thanks. 谢谢。

You can use direct child selector: 您可以使用direct child选择器:

$("> .subContainer", container);

If container is a jQuery object that refers to top-level .container element you can also use children method: 如果container是引用顶级.container元素的jQuery对象,您还可以使用children方法:

container.children('.subContainer');

Or find and first methods: findfirst方法:

container.find('.subContainer').first();

Based on Jquery: Get all elements of a class that are not decendents of an element with the same class name? 基于Jquery:获取一个类的所有元素,这些元素不是具有相同类名的元素的后代? I've developed the following solution. 我开发了以下解决方案。 Thanks to all. 谢谢大家。

$.fn.findButNotNested = function(selector, notInSelector) {
    var origElement = $(this);
    return origElement.find(selector).filter(function() {
        return origElement[0] == $(this).closest(notInSelector)[0];
    });
};

要获得第一个subContainer,您可以使用

$('.subContainer')[0]

This seems to work for my own uses... 这似乎适合我自己的用途......

$('.item').filter(function() { return $(this).parents('.item').length == 0; });

This returns only the #outer div. 这只返回#outer div。

<div class="item" id="outer">
    <div class="item" id="inner"></div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM