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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With