JQuery .not() is not the opposite of .is()

Published: 23-Jun-2015
Author: Steven Neiland
Site Url: http://www.neiland.net/article/jquery-not-is-not-the-opposite-of-is/

A coworker of mine got stung by this last week. While refactoring some logic he needed to reverse a result of a checkbox checked. Knowing that .is() returns a boolean he assumed that .not() would return the inverse.

This is what he was trying to get working, but as you will read on it did not work as expected.

// This does not work as expected
var notChecked = $('#somecheckbox').not(':checked');
if(notChecked){
// somelogic
} else {
// so other logic
}

.not() is a filtering function

Per the JQuery .not() documentation the value returned into the notChecked variable was actually a jquery object containing a subset of elements which do not match the checked rule and not a simple boolean.

The opposite of .is() is !.is()

Of course the solution is to simply use the javascript not operator "!" .

// This does work
var notChecked = !( $('#somecheckbox').is(':checked') );
if(notChecked){
// somelogic
} else {
// so other logic
}