Reputation: 94339
How can I select elements (using jQuery) that do not contain any elements?
For example, in the following tree:
<div class="a">
<div class="b">
<div class="c"></div>
</div>
<div class="d"></div>
<div class="e">Lorem</div>
</div>
Only the <div>
s with class
c
, d
, and e
will be selected.
Upvotes: 2
Views: 88
Reputation: 150283
$(':not(:has(*))')...
If you want to do it with the filter
function, be aware that > element
will be deprecated in next jQuery versions!
you can use this:
$('*').filter(function(){
return $('*', this).length == 0
})
:empty
selector won't work here because there is text node in the <div class="e">
use :empty
selector:
$(':empty')...
docs:
Description: Select all elements that have no children (including text nodes).
Upvotes: 3
Reputation: 318578
Try this:
$('*').filter(function() {
return $(this).children().length == 0;
});
You might also be able to use (faster) native DOM access inside the filter function:
return this.children.length == 0;
Upvotes: 3