All jQuery selectors and traversing functions returns a jQuery object. jQuery object is an Array-Like object that has properties and reference to core functions.
A small example to show the list of properties and functions readily available in jQuery object http://jsfiddle.net/Tj9e8/1/
When you call the jQuery function as $(selector)
, It creates a jQuery object with wrapped list of matched element(s) based on the selector.
For example: When you do $('#test')
, it creates a jQuery object and wraps DOM element with ID test
.
Check the below code snippet from jQuery's .init
function for handling for ID selector
elem = document.getElementById(match[2]);
//match[2] is string 'test' in '#test' that was passed to $('#test')
if (elem && elem.parentNode) {
if (elem.id !== match[2]) {
return rootjQuery.find(selector);
}
//below 2 lines allows the jQuery object to behave like array like objects
this.length = 1;
this[0] = elem; //elem is nothing but the dom node.
}
this.context = document;
this.selector = selector;
return this; //Returns jQuery object
For more information check out the .init
function code
Below is the snapshot of the $('#test')
.

As you can see the length is 0 but even still the $ function return jQuery object with length 0. This is to protect the next chained call instead of throwing an error.
In most cases, we select an element to run some function on it..
Ex: $('#test').addClass('example')
.
- Call's jQuery function using
$('#test')
with a string arguement '#test'
- jQuery call's
.init
above to determine the type of the argument and returns a jQuery object wrapped with matched elements(if any, else just jQuery object).
Call .addClass
on jQuery object, which internally iterate overs the list of matched elements and adds the class to the element. Below is snippet from .addClass
function code
if (value && typeof value === "string") {
classNames = value.split(core_rspace);
for (i = 0, l = this.length; i < l; i++) {
//^-- This is where it iterate over matched elements
elem = this[i];
if (elem.nodeType === 1) {
Now the points to note is,
- $ function always returns a jQuery object
The jQuery object is nothing but a javascript object with the following
a. Wrapped set of matched elements An example using .find
b. properties - Sample that lists properties
c. functions - Sample that lists functions
HTML:
<ul>
<li>Test</li>
<li class="red">Test</li>
<li>Test</li>
<li class="red">Test</li>
</ul>
JS:
var $lisample = $('ul').find('.red');
Not the wrapped set of matched elements as a result of .find
looks like below,

More reading
- How do jQuery objects imitate arrays?
- jQuery object and DOM element
- http://blog.buymeasoda.com/does-calling-the-jquery-function-return-an-ob