tags:

views:

74

answers:

3

For performance, which is faster?

$('#' + strControlId);

or

$('#' + strControlId, $('#' + strContextId));
A: 

I think the first one would be faster (it's doing less). Though when I think of using the context parameter, I think of doing things like accessing fields in a parent document from an iframe or something like:

var el = $('#' + strControlId, parent.document);

You could try a few benchmarks if you're really curious.

Cory Larson
I dont have access to the jquery environment to run a test, but I will when I get a chance
A: 

Since you are using an ID as your query I doubt it is any faster.

A good example would be this.

var inputs = $('input');
$('[class=this][name=that]', inputs).css('color', 'red');
ChaosPandion
+2  A: 

To answer your question, the first one will be faster. You will only be calling getElementById once.

One thing to note is the context parameter expects an HTML node and not a jQuery object. In your case, the second item is still searching in the Document rather than inside

$('#' + strContextId)

Make sure to add [0] onto the end of the jQuery object in order to pass the HTML node.

To test this, you can use the context property to check which context the selector is selecting from. For your examples above you can do this

console.log($('#' + strControlId).context);
console.log($('#' + strControlId, $('#' + strContextId)).context);

And you will find that they both return "Document" context. If you run

    console.log($('#' + strControlId, $('#' + strContextId)[0]).context);

It should return whatever element $('#' + strContextId) is pointing too.

T B
jQuery takes another jQuery or pure DOM element as a context, actually.
Will Morgan
So are you saying console.log($('#' + strControlId).context);console.log($('#' + strControlId, $('#' + strContextId)).context);will return the same thing? Open up firebug and run these commands on this pageconsole.log($('#header').context);console.log($('#header', $('.container')).context);You will find that they both return Document as the context. Does that not show that jQuery objects are not allowed?
T B