This is just a quick post to clear up any confusion over what kind of objects can be used as a context when performing a jQuery selector execution. Sometimes, when reviewing jQuery code, I see people make data type conversions in their context usage:
$( "div", myStuff[ 0 ] )
Here, you can see that the programmer is converting their "myStuff" jQuery collection into a single DOM node to be used as a selection context. This might make sense if the myStuff collection contained nodes within which you did not want to search; but more often than not, this data type conversion is entirely arbitrary. And, more than that, it is unnecessary, and inefficient.
If you look at the documentation for the $() method, you will see that the context argument can be a DOM element, a document, or a jQuery object. And, if you check the actual source code, you will see that the use of the context:
$( selector, context )
... is actually turned into a find() method internally:
$( context ).find( selector )
To optimize this execution, jQuery actually checks to see if the given context is a jQuery object; if it is, it performs the find() method call directly on the given context. If the given context is a DOM element, however, it first converts it to a jQuery object and then executes the find() method. So, actually, if you extract a DOM node as the context from a given jQuery object, you're slowing down execution, forcing jQuery to re-package the DOM node as a jQuery object.
When using a context, I personally find the find() method to be easier to read; but, if you're going to use the context argument in the $() method, just remember that it can be a jQuery object; there's no need to pass in a DOM element if you don't already have one.
Want to use code from this post? Check out the license.