2

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!'.

zkwentz
  • 1,095
  • 5
  • 22
  • 44

3 Answers3

7

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
5

Try using the jQuery :not selector

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

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

Musa
  • 96,336
  • 17
  • 118
  • 137
1

Try

var a = $('.a'), not = a.find('.a');
a.not(not);

selector profiling

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Why is it that the concatenated filter performs so poorly? – zkwentz Jul 17 '13 at 04:22
  • 1
    @wentz__: Probably because jQuery has to parse the selector, realize that it's not valid CSS (see http://stackoverflow.com/questions/10711730/whats-the-difference-in-the-not-selector-between-jquery-and-css), and parse it some more and turn it into a filter. This is why I use the filter method instead if I know I can't do it with a proper CSS selector - because the selector eventually gets converted into a method call anyway. – BoltClock Jul 17 '13 at 04:44