Does jQuery always return array?

2020-08-09 17:30发布

Does jQuery always return array when selecting element (of course if at least one element exists)? Example:

$('#Myelement')
$('div')
$('tbody')

What if the selector is an ID? What if the selector is an element but has only one occurrence?

2条回答
对你真心纯属浪费
2楼-- · 2020-08-09 17:44

Because $([selector]) is like a shortcut of $.find([selector]) which is an element search.

That's anything executed with such jQuery functions may return one or more results, since you're searching rather than "selecting a result".

查看更多
虎瘦雄心在
3楼-- · 2020-08-09 17:46

The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.

That way you can always call a method that is supposed to affect the elements found, even if there are no elements that matched. If the jQuery object contains no elements, it will simply do nothing.

If you need to know if a jQuery object contains any elements, you can use the length property.

查看更多
登录 后发表回答