FAR too often I have seen people who are new to jQuery make the same
irritating mistake, which I want to address once and for all. jQuery has an
.is() method, which checks to see if at least
one element in the current jQuery selection matches a selector, and returns a
boolean reflecting this fact. For instance:
1 2 3 4 5 6 7 | |
This is all well and good, and very convenient. While some purists might
object to the use of this method (because of “overhead”) compared to an
explicit check on, well, whatever it is you’re trying to check, the simplicity
of .is() is seductive. However, its existence leads a lot of people to make
the same very bad assumption about jQuery’s
.not() method.
1 2 3 4 5 | |
WHY?!? You ask? Because jQuery’s .not() method is a filtering method, it
does not return a boolean value. .not() is, in fact, the opposite of
.filter(), checking each element in the
matched set and returning only those that do not match the selector. Given
the following DOM:
1 2 3 4 | |
1 2 3 4 | |
Since .not() is a filtering method, it returns a jQuery object, which, like
any object ever anywhere always, will return true when tested for its boolean-
ness. Thus, the .not() method simply is not appropriate for doing checks
such as the one above. Luckily, JavaScript provides us with a not operator !,
which is the right way to test for the opposite of .is(). For
instance,
1 2 3 | |
While this seems incredibly obvious to many, I have seen this errant
assumption far too many times to remain silent any longer! So say it loudly,
proudly with me now: The opposite of jQuery’s .is() method is not .not(),
it is !.is()