14

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 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

8 Comments

In my opinion, your second statement isn't a good explanation, because this isn't why jQuery returns an array. It's because $() finds elements matching a given selector, so you can't expect the element having some id, but a result containing the element having some id.
@Matías Fidemraizer: The second paragraph is not an explanation of why the methods returns an array, it's an explanation of how you can use that to your advantage. I'm afraid that I don't understand what you mean with the explanation that you offer.
But when I do $('td')[0].html('hi'), it gives me an exception, it says that index has no .html method, meaning the elements on the array returned by jQuery are not part of the jQuery object. Am I wrong?
@domanokz: The jQuery object contains elements, it doesn't contain jQuery objects. If you use [0] to get an element out of the jQUery object, it's a plain DOM element that you can't use jQuery methods on. You can use the first method to limit the result to the first element: $('td').first().html('hi'), or you can wrap the element in a jQuery object: $($('td')[0]).html('hi') (but that will cause an error if the selector found no elements).
@Guffa: It's actually quite the opposite. A jQuery Object is not based on an array, it's an object which behaves "array-like" by adding .length and .splice()
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.