views:

7965

answers:

2

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?

+21  A: 

Children only looks at the immediate children of the node, while find traverses the entire DOM below the node, so children will be faster. Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM.

tvanfosson
D'oh, too slow. ;)
John Feminella
Sure, but what happens if the parent element only has child nodes? I'm going to do some profiling on this.
jason
+4  A: 

Those won't necessarily give the same result: find() will get you any descendant node, whereas children() will only get you immediate children that match.

Thus, find() will be slower since it must search for every descendant node that could be a match, and not just immediate children.

John Feminella