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?
@zero298 The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned. So no boolean result.
returning true or false indicates that whether execution should continue or stop right there. So just an example <input type="button" onclick="return func();" /> Now if func() is defined like this function func() { // do something return false; } the click event will never get executed.
Note that these exceptions are not part of the C language itself, but rather with commonly-used C functions. Show activity on this post. In an if statement, or any case where a boolean value (True or false) is being tested, in C, at least, 0 represents false, and any nonzero integer represents true.
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.
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()
.
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.
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With