How can one get all the leaf nodes, let's say divs, from the DOM? I am trying to think of an optimal solution, if there's no easy and magical selector for this. I thought of using the "reachedElem.find('div').length == 0" but I am not sure if this is the right direction. Any ideas?
You can go with following selector
$('div:not(:has(*))')
Above selector will select all the DIVs who don't have any children.
If you really want something efficient, avoid the complex :not(:has(*))
selector:
$("div").filter(
function(index) {
var isLeaf = $(this).children().length === 0;
return isLeaf;
}
);
I found out it's twice as efficient as eHussain's suggestion, or even faster.
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