Having the following html snippet
<div class="something">
<p>Some text</p>
</div>
<div class="somethingElse">
<p>some other text</p>
</div>
I think the following jquery snippets are identical (will have the same result):
$(".something").find("p").css("border", "1px solid red");
$("p", ".something").css("border", "1px solid red");
My question is, whether one snippet is better than the other and should be used
The calls are not identical.
According Brandon Aaron, who apparently worked on jQuery, and also according to the live tests here, the find method is always faster. See results in the screenshot below. Please comment if I am missing something.
With a 10% or greater difference in speed, depending on browser, it definitely seems worth using find.
Further explanation at Brandon's site is here.
Find is better, by 40%:
http://jsperf.com/jquery-find-vs-context-2/13
Note the difference:
when passing
$myDiv
, the jQuery element as the context, its about 10% slower than $.find. when passing in#myDiv
, the jQuery selector as the context, its 40% slower than $.find.$.find > context.
Both calls are identical. The latter call is translated into the former one. If you want to omit the translation step, use the former one.
I can think of one use case where using the
context
form might be preferable - in the case where the context is contained in a variable which might be null.For example:
The second time
do_something()
is called, if we had used$parent_element.find()
it would have failed, whereas in this example, if$parent_element
is undefined or empty the context is null, thus: the entire document.Admittedly this is an edge case, but it just came up in something I was working on, so thought I'd put it here for posterity.