mix
mix

Reputation: 7151

opposite of jQuery find() that isn't not()?

Given the following HTML, what jQuery selector would select the last 'blah blah' span but not the first?

<div class='d1'>
  <span>
    <a>blee
      <span> <!-- don't select this span -->
        <span>blah</span> blah
      </span>
    </a>
  </span>
</div>

<br/>

<div class='d1'>
  <span>
    <a>blee
      <span> <!-- select this span -->
        blah blah
      </span>
    </a>
  </span>
</div>

I've tried variations using not() but can't figure it out. It seems like what I need is a selector that finds the first span, but then excludes it if it contains another span. Something like:

$('.d1 span a span').not(':has("span")')

but that doesn't do it. What am I missing?

Upvotes: 4

Views: 9178

Answers (5)

Ram
Ram

Reputation: 144719

Try this:

$('.dl:last span:not(:has(*))')

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206506

demo jsbin

$('a>span:not(:first)')

Upvotes: 0

Blender
Blender

Reputation: 298432

Select only the child spans of that a:

$('.d1 span a > span:not(:has(span))')

Demo: http://jsfiddle.net/Blender/eSDrK/1/

Upvotes: 1

Gromer
Gromer

Reputation: 9931

If I'm understanding your question correctly, you want this selector:

$('div.d1 span:last')

Fiddle showing it in action: http://jsfiddle.net/aWCsT/

Upvotes: 2

James Allardice
James Allardice

Reputation: 166031

If I've understood your question correctly, all you're missing is a child combinator:

$('.d1 span a > span').not(':has("span")')

Here's a working example.

The reason you need this is that .d1 span a span will match both span descendants of the a element in the first .d1 element. The .not() call will exclude the outer one, but the inner one will still be part of the matched set. By adding the child combinator, only the outer span is selected, and then removed by the call to .not().

Upvotes: 6

Related Questions