Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 775
Mateu Avatar asked Dec 28 '12 15:12

Mateu


People also ask

How do you get children of children in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.

Which will select all direct child elements in jQuery?

The ("parent > child") selector selects all elements that are a direct child of the specified element.

How do I get grandchildren in jQuery?

jQuery find() Method The find() method returns descendant elements of the selected element, all the way down to the last descendant.


2 Answers

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();
like image 135
undefined Avatar answered Sep 24 '22 01:09

undefined


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];
    });
};
like image 26
Mateu Avatar answered Sep 24 '22 01:09

Mateu