Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery always return array?

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?

like image 669
dpp Avatar asked Aug 08 '11 09:08

dpp


People also ask

What does jQuery function return?

jQuery() Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.

Does find return jQuery object?

find() returns an object even when there's no matching child element in the DOM. Save this question.

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.

What is array in jQuery?

The jQuery inArray() method is used to find a specific value in the given array. If the value found, the method returns the index value, i.e., the position of the item. Otherwise, if the value is not present or not found, the inArray() method returns -1.


2 Answers

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.

like image 150
Guffa Avatar answered Oct 13 '22 08:10

Guffa


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

like image 26
Matías Fidemraizer Avatar answered Oct 13 '22 10:10

Matías Fidemraizer