Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an element does NOT have a specific class?

People also ask

What does classList do in JavaScript?

JavaScript classList is a DOM property of JavaScript that allows for styling the CSS (Cascading Style Sheet) classes of an element. JavaScript classList is a read-only property that returns the names of the CSS classes.

How do you check whether a class is used in jQuery or not?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".


if (!$(this).hasClass("test")) {

sdleihssirhc's answer is of course the correct one for the case in the question, but just as a reference if you need to select elements that don't have a certain class, you can use the not selector:

// select all divs that don't have class test
$( 'div' ).not( ".test" );
$( 'div:not(.test)' );  // <-- alternative 

Select element (or group of elements) having class "abc", not having class "xyz":

    $('.abc:not(".xyz")')

When selecting regular CSS you can use .abc:not(.xyz).


You can try this:

<div id="div1" class="myClass">there is a class</div>
<div id="div2"> there is no class2 </div>

$(document).ready(function(){
    $("#div2").not('.myClass');  // do not have `myClass` class.
});

use the .not() method and check for an attribute:

$('p').not('[class]');

Check it here: http://jsfiddle.net/AWb79/