Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to get leaf nodes with jQuery?

Tags:

jquery

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?

like image 944
Ricardo Avatar asked Jan 05 '11 09:01

Ricardo


2 Answers

You can go with following selector

$('div:not(:has(*))')

Above selector will select all the DIVs who don't have any children.

like image 137
eHussain Avatar answered Oct 14 '22 10:10

eHussain


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.

like image 44
Romain Piel Avatar answered Oct 14 '22 10:10

Romain Piel