What does jquery $ actually return?

It doesn't return an array, it returns a jQuery object. The jQuery object is what contains all the special jQuery methods.

It never returns null, or another type. If one element is found, the jQuery object will have only one child. If no elements are found, the jQuery object will be empty.


As another answerer mentioned, it always returns the jQuery object.

This object always contains an array of elements (even if it is an empty array, or an array with just one object).

If you'd like to use the returned object "directly", as in, as a plain element, you can do one of the following:

$('selector')[0] // element
$('selector').get(0) // element
$('selector').length // number of elements in the array

From Rick Strahl's description:

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example). More importantly, you can also apply jQuery functions against all the selected elements.

About returning nothing:

Does it always return an array? Does it return null?

You always get the same thing back, whether or not it has any contents is the question. Typically you can check this by using .val() (e.g. $('.myElem').val())

Tags:

Jquery