Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is fastest children() or find() in jQuery?

To select a child node in jQuery one can use children() but also find().

For example:

$(this).children('.foo');

gives the same result as:

$(this).find('.foo');

Now, which option is fastest or preferred and why?

like image 900
bart Avatar asked Mar 15 '09 15:03

bart


People also ask

Which is the fastest selector in jQuery?

ID and Element selector are the fastest selectors in jQuery.

What is the difference between using Find () and children ()?

The find() method traverses the entire Dom whereas the children() method gets the immediate children of the node. The children() method is to get the immediate children of the node.

What is jQuery child method?

jQuery children() Method The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.


1 Answers

children() only looks at the immediate children of the node, while find() traverses the entire DOM below the node, so children() should be faster given equivalent implementations. However, find() uses native browser methods, while children() uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.

Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM, i.e., choose the appropriate method based on the results you desire, not the speed of the method. If performance is truly an issue, then experiment to find the best solution and use that (or see some of the benchmarks in the other answers here).

like image 111
tvanfosson Avatar answered Oct 12 '22 13:10

tvanfosson