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?
ID and Element selector are the fastest selectors in jQuery.
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.
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.
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.
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).
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