jquery find versus context selection

jquery find versus context selection  using -'jquery,jquery-selectors'

Having the following html snippet

<div class="something">
    <p>Some text</p>
<div class="somethingElse">
    <p>some other text</p>

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

asked Oct 13, 2015 by shegokar.anjeet
0 votes

3 Answers

0 votes

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

answered Oct 13, 2015 by rajesh
0 votes

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

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.

answered Oct 13, 2015 by gauravsinghal83
0 votes

Find is better, by 40%:


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.

answered Oct 13, 2015 by dhananjayksharma