Get up to 80 % extra points for free! More info:

Lesson 5 - Classes in jQuery (DOM)

In the previous lesson, Removing contents in jQuery (DOM), we focused on removing content. In today's JavaScript tutorial, we're going to show how to use jQuery to manipulate with classes. As usual, the jQuery library provides several useful methods for this purpose, making our lives easier.

We add and remove classes of different HTML elements to change their styles. Switching styles using classes is much more elegant and simple compared to modifying styles directly.

The page skeleton

Let's start as usual by creating an HTML file and a JS file.

JavaScript

We'll insert the basic jQuery structure for handling the Document ready event inside the JS file:

$(function() {
    // The code here is executed not before the page is loaded
});

HTML

We'll insert a list of the most used languages for web development inside the HTML file:

<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li>JS</li>
    <li>PHP</li>
    <li>ASP .NET</li>
    <li>JAVA</li>
</ul>

CSS

Let's add styles as well:

ul {
    list-style-type: none;
}

ul li {
    background : #0080C0;
    color      : #ededed;
    width      : 100px;
    border     : 2px solid #004080;
    margin     : 10px 20px;
    padding    : 5px 10px;
    font-family: 'Open Sans';
    font-size  : 18px;
}

.active {
    background : #ed1c24;
    color      : #ededed;
    border     : 2px solid #7f0011;
}

Don't forget to link JS and CSS files in <head> of the HTML document.

So far, the document looks as follows:

Your page
localhost

The methods we're going to work with today are addClass(), removeClass(), hasClass(), and toggleClass().

addClass()

First, we'll introduce the addClass() method which assigns a class or classes to a given element or elements. If we wanted to assign multiple classes, we'll separate them with spaces.

Example #1

Let's add id="html" to the first list item (HTML) and assign a .myClass class to it using jQuery.

$('#html').addClass('myClass');

As we can see, the .myClass class has actually appeared on our element with the #html id.

Your page
localhost

Example #2

Let's try to assign a class using a more practical example. We'll assign the .active class when an item is clicked. The class will color the given item.

We'll use the on('click') event which we'll bind to the ul li elements. In an anonymous function, we'll call addClass() with the 'active' parameter on $(this).

$('ul li').on('click', function() {
    $(this).addClass('active');
});

The code works. You can try it in the live demo below:

Your page
localhost

removeClass()

The removeClass() method works the very opposite way. If an element or elements contain a given class, it removes it.

Again, we can remove multiple classes if we separate them by spaces.

Example #3

Now, we'll assign the .active class to all the list items and create a reverse example to the previous one. This time, we'll remove the active class when an item is clicked.

$('ul li').on('click', function() {
    $(this).removeClass('active');
});

You can try the result:

Your page
localhost

Great, but what would we do if we wanted to assign the class back when it's missing and remove it if it's present?

We can use the hasClass() method for that.

hasClass()

The hasClass() method returns a boolean value (i.e. true or false). It doesn't differ from its precedents in its syntax in any way.

$(selector).hasClass('myClass');

Example #4

Now let's have a look at how to remove the class and or put it back again when clicked. We're going to use the hasClass() method for it.

First, as before, we'll bind the on('click') event of the list items and pass an anonymous function as the second argument.

$('ul li').on('click', function() {

});

We'll place the following code inside the anonymous function. We'll add a condition if the $(this) element has the .active class assigned. The this variable in the callback function of an event always contains the element which caused the event.

$('ul li').on('click', function() {
    if ($(this).hasClass('active')) {
        $(this).removeClass('active');
    } else {
        $(this).addClass('active');
    }
});

The live demo:

Your page
localhost

After several clicks we can see that everything works as it should. However, our code is relatively long, and if we don't want to do anything other than adding or removing the class, this functionality can be achieved much more elegantly. To do so, we'll use the toggleClass() method.

toggleClass()

The toggleClass() method toggles the class of a given element or elements. That means that if the class is not assigned to an element, it assigns it. Otherwise, it removes the class.

$(selector).toggleClass('myClass');

We can also define a condition to assign the class. For example:

$(selector).toggleClass('myClass', number % 2 === 0);

The code above assigns the .myClass class to the selected elements only if the value of a number variable is even (i.e. the remainder after division by 2 is 0).

Example #5

Now, let's show our previous example of toggling a class, this time using toggleClass(). As before, we'll prepare an event first:

$('ul li').on('click', function() {

});

Now, instead of if, we'll use toggleClass().

$('ul li').on('click', function() {
    $(this).toggleClass('active');
});

We can toggle all elements nicely using a very short code. jQuery is just awesome for this.

Your page
localhost

Example #6

But that's not all we can do with these methods. Instead of a class name, we can also pass an anonymous function that will contain different conditions and return different class names.

Let's show, for example, a function that assigns the active class to all the items which don't contain the text PHP. To be illustrative, let's also assign an .iWannaBePHP class to the items which don't contain 'PHP'.

We'll call the addClass() method on the list items and pass an anonymous function instead of the class name:

$('ul li').addClass(function() {

});

We'll write this simple condition inside the function:

$('ul li').addClass(function() {
    if ($(this).text() == 'PHP') {
        return 'active';
    }
    return 'iWannaBePHP';
});

Of course, we can make the condition shorter, e.g. like this:

$('ul li').addClass(function() {
    return ($(this).text() == 'PHP') ? 'active' : 'iWannaBePHP';
});

When we open the example, only the PHP item is highlighted. We can also see the .iWannaBePHP class assigned to the other items.

Your page
localhost

You may wonder how is it possible that only 'PHP' is highlighted without using such a method like each() or something similar. The jQuery library does not distinguish whether one or more elements are selected, all its methods are always called for all the elements in the selection.

In the next lesson, Selectors in jQuery, part one, we'll do an overview of the selectors we can use in jQuery.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 1x (1.73 kB)
Application includes source codes in language JavaScript

 

Previous article
Removing contents in jQuery (DOM)
All articles in this section
jQuery Basics
Skip article
(not recommended)
Selectors in jQuery, part one
Article has been written for you by Honza Bittner
Avatar
User rating:
2 votes
Everything is possible.
Activities