Imagine this simplified markup:
<div id="header">
<!-- Other things.... -->
<div id="detail">
</div>
</div>
and assume you already have this code:
var $hdr = $("#header");
Is there any speed difference for jQuery to lookup "detail" this way:
var $detail = $("#detail", $hdr);
vs
var $detail = $("#detail");
Since detail is being looked up by ID?
No, you don't have to do that. Since id is unique in a document no need to add any other optimization.
I would go with
var $detail = $("#detail");
No. Passing a context will actually make it slower. The relevant source code from jQuery is given below with an explanation.
This code basically says:
And here's the stripped out source..
init: function( selector, context ) {
...
if ( typeof selector === "string" ) {
...
// This gets ignored because we passed a context
// document.getElementById() isn't called directly
if ( match && (match[1] || !context) ) {
...
} else {
elem = document.getElementById( match[2] );
...
}
...
// Either this gets executed if a jQuery wrapped context was passed
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
}
// Or this gets executed, if a simple selector was passed as context
} else {
return jQuery( context ).find( selector );
}
...
}
match
is the resulting array of a regular expression to find out if the selector is either an HTML string, or an id expression. If it's an HTML string, then match[1] will be populated. If it's an id (#someId), thenmatch[2]
will be populated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With