Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 829
mix Avatar asked Dec 26 '22 17:12

mix


1 Answers

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().

like image 146
James Allardice Avatar answered Jan 15 '23 10:01

James Allardice