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

Author: Steven Neiland
Published:

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

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
}

Reader Comments

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain advertisments or appear to be created for the purpose of link building, will not be published.

Archives Blog Listing