mas-designs
mas-designs

Reputation: 7536

Why does .find() always return true?

It seems like jQuery's .find() method always returns true. But that's not really useful because you have do additionally check the length of the returned object to see if it really exists.

Anyone got a good explanation for that behaviour?

Upvotes: 9

Views: 10680

Answers (5)

Blaise
Blaise

Reputation: 13489

Example how to check if any elements where matched:

if ( $('body').find('li').length ) {
    // at least one li was found
} else {
   // no li's where found
}

$() and selector methods like find() and filter() always return a jQuery object. This is so you can chain methods. You could do something like

$('body').find('li').add('<p>')

This finds all list elements in the body, and adds a paragraph to all. If $('body').find('li') would return false because it didn't contain any li's, the add() method would throw an error, because you cannot do false.add().

Upvotes: 6

Tadeck
Tadeck

Reputation: 137410

.find() method of jQuery returns jQuery object, which could be evaluated to true in some cases. But in fact comparing it strictly (===) with true will fail (the comparison will return false).

This is why you should use strict comparison (=== instead of ==) and check for .length property when counting returned elements (this is true also about Array objects).

It is completely reasonable, as the jQuery object is only a container for elements you have found. It must have jQuery methods (the ones you can call on the result of .find()), thus it must not be a boolean.

Upvotes: 3

Skyrim
Skyrim

Reputation: 865

Remember

$('selector').find('subselector')

will return the same result set as

$('subselector', 'selector') or $('selector subselector')

One of the utilities of find() resides in chaining

$('div table').css('width', '100px')
              .find('tr').css('background-color', 'Red');

Upvotes: 0

jensgram
jensgram

Reputation: 31498

Anyone got a good explanation for that habit ?

If .find() were to return a Boolean value instead of a jQuery object, you could not use it for chaining which is one of the overall goals of jQuery.

Upvotes: 7

Dogbert
Dogbert

Reputation: 222278

It doesn't return true. It returns an empty set of elements, which is true if you do ==. You need to check .length and check if 0 elements were returned.

Upvotes: 13

Related Questions