Does jQuery always return array?

2020-08-09 17:19发布

问题:

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?

回答1:

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.



回答2:

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".