Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select elements only if they aren't nested within like elements

Assuming the following:

<div class="a"> <!-- select -->
  <div class="b">
    <div class="a"> <!-- skip -->
    </div>
  </div>
</div>

<div class="b">
   <div class="a"> <!-- select -->
     <div class="b">
        <div class="a"> <!-- skip -->

        </div>
     </div>
   </div>
</div>

<div class="a"> <!-- select -->

</div>

How do I only select the outermost $('.a') elements?

Edit: A helpful JSFiddle, in this example, only 'a' should be selected, not 'a!'.

like image 785
zkwentz Avatar asked Jun 08 '26 14:06

zkwentz


2 Answers

This is where filter methods come in handy:

$('.a').not('.a .a');

This excludes any .a that is nested within another .a so you only get the outermost ones, regardless of whether the outermost ones are themselves nested within other elements.

like image 103
BoltClock Avatar answered Jun 11 '26 03:06

BoltClock


Try using the jQuery :not selector

$('.a:not(.a .a)')

http://jsfiddle.net/7E7Mk/1/

like image 38
Musa Avatar answered Jun 11 '26 03:06

Musa