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:
Here’s a working example.
The reason you need this is that
.d1 span a spanwill match bothspandescendants of theaelement in the first.d1element. 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 outerspanis selected, and then removed by the call to.not().