What does jquery $ actually return?

2019-01-01 02:16发布

I have read the JQuery documentation, and while much attention is devoted to what you should pass the function, I don't see any information on what it actually returns.

In particular, does it always return an array, even if only one element is found? Does it return null when nothing is found? Where is this documented?

I understand that jquery methods can be applied to the return value, but what if I want to just use the return value directly?

标签: jquery
9条回答
怪性笑人.
2楼-- · 2019-01-01 02:40

Their documentation lists a few of the core calls you can use with "$" and what they return

查看更多
临风纵饮
3楼-- · 2019-01-01 02:47

From the jQuery documentation:

The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().

查看更多
ら面具成の殇う
4楼-- · 2019-01-01 02:49

The jQuery function (i.e. "$") always returns a jQuery object in every instance.

查看更多
十年一品温如言
5楼-- · 2019-01-01 02:53

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.

查看更多
余欢
6楼-- · 2019-01-01 02:53

According to firebug, it returns an array of objects that match to your selector. But this array is a jQuery object, that more methods than a simple Array.

查看更多
梦寄多情
7楼-- · 2019-01-01 02:55

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
查看更多
登录 后发表回答