What is the fastest method for selecting descendant elements in jQuery?

Marko picture Marko · Jul 5, 2010 · Viewed 19k times · Source

As far is I know, there are a number of ways of selecting child elements in jQuery.

//Store parent in a variable  
var $parent = $("#parent");

Method 1 (by using a scope)

$(".child", $parent).show();

Method 2 (the find() method)

$parent.find(".child").show();

Method 3 (For immediate children only)

$parent.children(".child").show();

Method 4 (via CSS selector) - suggested by @spinon

$("#parent > .child").show();

Method 5 (identical to Method 2) - according to @Kai

$("#parent .child").show();

I'm not familiar with profiling to be able to investigate this on my own, so I would love to see what you have to say.

P.S. I understand this is a possible duplicate of this question but it doesn't cover all methods.

Answer

Aaron Harun picture Aaron Harun · Jul 5, 2010

Method 1 and method 2 are identical with the only difference is that method 1 needs to parse the scope passed and translate it to a call to $parent.find(".child").show();.

Method 4 and Method 5 both need to parse the selector and then just call: $('#parent').children().filter('.child') and $('#parent').filter('.child') respectively.

So method 3 will always be the fastest because it needs to do the least amount of work and uses the most direct method to get first-level children.

Based on Anurag's revised speed tests here: http://jsfiddle.net/QLV9y/1/

Speed test: (More is Better)

On Chrome, Method 3 is the best then method 1/2 and then 4/5

enter image description here

On Firefox, Method 3 is still best then method 1/2 and then 4/5

enter image description here

On Opera, Method 3 is still best then method 4/5 and then 1/2

enter image description here

On IE 8, while slower overall than other browsers, it still follows the Method 3, 1,2,4,5 ordering.

enter image description here

Overall, method 3 is the overal best method to use as it is called directly and it doesn't need to traverse more than one level of child elements unlike method 1/2 and it doesn't need to be parsed like method 4/5

Though, keep in mind that in some of these we are comparing apples to oranges as Method 5 looks at all children instead of first-level ones.