简体   繁体   中英

jquery selecting children not nested in a child

I have some problems with a jQuery selector.

Let's say I have the following html where (...) stands for an undefined number of html tags.

(...)
<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). I want a jquery that selects the first subcontainer but not the nested one. If I use $(".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:

$("> .subContainer", container);

If container is a jQuery object that refers to top-level .container element you can also use children method:

container.children('.subContainer');

Or find and first methods:

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? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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