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?
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).