adam j. sontag

slightly more like a website than before

The opposite of jQuery's .is() method is not .not(), it is !.is()

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
if ($("#someCheckbox").is(":checked")) {
  //do something if the checkbox is checked
}
if ($("div').is("[data-pants]")) {
// do something if at least one div has
// a data-attribute called 'data-pants'
}

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 DOESN'T THIS WORKS?!?
// IT'S ALWAYS SAY TRUE!  WHY?!
if ($("#someCheckbox").not(":checked")) {
  // do something if the checkbox is NOT checked
}

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
<p>Hello</p>
<p>There</p>
<p class="greeted">Sirs</p>
<p>Have a great day!</p>
1
2
3
4
var paragrafz = $("p");
paragrafz.length == 4;
paragrafz.filter(".greeted").length == 1
paragrafz.not(".greeted").length == 3;

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
if (!$("#someCheckbox").is(":checked")) {
  // do something if the checkbox is NOT checked
}

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()

Comments