Topic on Talk:Learning JavaScript

Selector performance, contexts

6
Yair rand (talkcontribs)

The optimized example given in this section is $( '#bodyContent' ).find( 'li > a' );, but wouldn't it be better to use $( 'li > a', '#bodyContent' );?

Krinkle (talkcontribs)

Although it's not bad, the syntax you proposed is slower.

What that does is, it goes through all of jQuery's initializer and eventually at the bottom it calls (literally): $( context ).find( selector ).

The reason jQuery supports the syntax is, for example, in case plugins provide a variable as context that would otherwise cause plugins from having to write code like this:

if ( context.jquery ) {
  return context.find( '...' );
} else {
  return $( ' ... ', context );
}

instead you can use:

  return $( '...', context );

And jQuery will figure it out, after it doesn't recognize the standard syntax.

However if you know what you're doing and the context is not variable but known, it's much better to just do $(context).find(selector); directly.

Dantman (talkcontribs)

That's one reason for the context argument, the other reason is more like for things like:

$( '...', someIframe.contentDocument );

The idea of passing a selector as the second parameter for context is completely and absolutely unintuitive, you end up with the first selector run being written after the second one run, it's completely different from the way a normal person should expect to read it.

No good jQuery developer will suggest or thank you for using that.

In fact it's so unwelcome that the jQuery documentation doesn't even admit the fact that jQuery will technically accept a selector there.

context
A DOM Element, Document, or jQuery to use as context
Krinkle (talkcontribs)

In that case, I'd still recomend:

$( someIframe.contentDocument ).find( '...' );

Even if it was just to make it easier to read, and easier to cache the root jQuery object, eg.:

var $root = $( someIframe.contentDocument ),
    $foos = $root.find( '#foo > .items' ),
    $bars = $root.find( '#bar > .items' );

I didn't know using a selector String as context was possible (as it isn't documented at all). That enforces even more that it shouldn't be used.

Neelasdfsd (talkcontribs)

swipe and nice bouye

Neelasdfsd (talkcontribs)

every body come vot e

Reply to "Selector performance, contexts"