Jquery opposite of .hasClass()?

Why not simply:

if (!el.hasClass('foo')) {
  // code
}

You can use

el.is('.oneClass:not(.secondClass)')

if you need check more than one class or

el.is(':not(.secondClass)')

if you need check only one class.


if (!element.hasClass('classname')) {
    ...
}

More generally in javascript, to check the opposite of a boolean result, use the logical NOT operator !:

var isValid = false;
if (!isValid) {
    // execute if isValid = false;
}

For your question, .hasClass() returns a boolean if the element has the specified class, so if you have the expression:

<div class="someClass"></div>

if ($('div').hasClass('someClass')) {
    // will execute
}

to check if it does not have that class:

if (!$('div').hasClass('someClass')) {
    // will not get here because our element has the class "someClass"
}

When selecting elements, if you want to avoid those who have a certain class, you can use the :not() pseudo-selector:

$('div:not(.someClass)')

About the :not() selector

Tags:

Jquery

Class