jquery find versus context selection

JqueryJquery Selectors

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Results of performance comparison between jQuery context and jQuery find method

Solution 2 - Jquery

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.

Solution 3 - Jquery

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:

// Only affect matching items that are descendants of '#parent'
do_something( $( '#parent' ) );
// Affect all matching items
do_something();

function do_something( $parent_element ){
  $( '.child', $parent_element ).each( function(){ } );
}

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.

Solution 4 - Jquery

Find is better, by 40%:

http://jsperf.com/jquery-find-vs-context-2/13

Note the difference:

$myDiv = $("myDiv")
myDiv = "#myDiv"

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionharpaxView Question on Stackoverflow
Solution 1 - JqueryBrianFinkelView Answer on Stackoverflow
Solution 2 - JqueryGumboView Answer on Stackoverflow
Solution 3 - JqueryTom AugerView Answer on Stackoverflow
Solution 4 - JquerydylanjhaView Answer on Stackoverflow