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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With