Using Classes in jQuery

Adding a class

To add a class to an element, the method is used addClass(‘classnames’), which takes the name of the class as a parameter. Since several classes can be defined for one element, in this case we can also pass a string containing several classes separated by spaces to the addClass method:

$('ul').first().addClass("redStyle");
// adding two classes
$('div').first().addClass("black visible");

Deleting a class

The method is used to delete a class removeClass(‘classnames’). This method also accepts a set of class names separated by spaces. And if the element has such a class, then it is removed:

$('div').first().removeClass("black visible");

Checking classes. hasClass method

It is often necessary to check if an element has a class, especially if classes are added dynamically. In this case, the method can help us hasClass(‘classnames’). And if it contains a class, then this method returns true, otherwise false.

if($('ul').first().hasClass("redStyle")){
    console.log('The list contains the class redStyle');
}
else{
    console.log('The list does not contain the redStyle class');
}

Switching classes

Class switching is done using the toggleClass(‘classname’). The name of the class that will be assigned to the element is taken as a parameter. For example, let’s switch the class of the button when it is pressed:

<style>
.redStyle {color:red;}
</style>
 
<button class="redStyle">Toggle style</button>

<script type="text/javascript">
$(function(){
        $('button').click(function(){
            $(this).toggleClass("redStyle");
        })
});
 
</script>

Here we attach an event handler to the button click. The handler itself is passed as a function as a parameter. In this function, we switch the redStyle class using the method toggleClass(“redStyle”)- if the class exists, it is removed, and if it does not exist, then it is added.