Manipulating Element Classes with jQuery

Explores jQuery's methods for working specifically with classes: hasClass(), addClass(), removeClass() and toggleClass().

jQuery Logo

In Manipulating Element Attributes with jQuery, you explored 2 jQuery methods for working with element attributes: attr() to read, add, and change attributes, and removeAttr() to remove attributes.

In this tutorial you'll look at some jQuery methods for working specifically with the class attributes of elements:

  • hasClass() to check if an element has a certain class
  • addClass() to add a class to an element
  • removeClass() to remove a class from an element
  • toggleClass() to add a class to an element if it doesn't already have it, or remove a class if it does

While you can use attr() and removeAttr() to work with classes, these class-specific methods are more useful because:

  • They're easier to use on classes
  • You tend to work with CSS classes a lot with jQuery, and
  • class attribute values often contain multiple class names, making them more complex to deal with than most other attributes.

Let's take a look at each of these methods in turn.

Checking for a class with hasClass()

The first method is hasClass(), which you can use to test if 1 or more elements have a certain class. To use it, pass in the class name you want to look for. hasClass() returns true if any elements in the jQuery object have that class, or false otherwise.

Here's a complete example that shows hasClass() in action. The script pops up an alert box saying "Found", because the first div in the page contains the class "summary":


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {

  // Display "Found" if any divs in the page have a class called "summary"
  if ( $('div').hasClass('summary') ) alert( 'Found' );
}

</script>
</head>
<body>
  <div class="header summary">Here's a summary</div>
  <div class="header main">Here's another div</div>
  <div class="content">Here's another div</div>
</body>
</html>

Adding classes with addClass()

If you want to add a class to an element, use addClass(), passing in the name of the class to add:


// Add the class 'summary' to #myDiv
 $('#myDiv').addClass('summary');

If the element already has the specified class then addClass() does nothing.

You can also add the same class to many elements at once:


// Add the class 'summary' to all divs in the page
$('div').addClass('summary');

To add multiple classes, separate the class names with spaces:


// Add the classes 'header' and 'summary' to #myDiv
$('#myDiv').addClass('header summary');

Finally, you can pass a callback function to addClass() in much the same way as attr(). The callback function should accept 2 arguments:

  • The index position of the current element in the set (starting from zero)
  • The old value of the class attribute (if any) for the current element

The function should return the class name to add (or multiple class names separated by spaces).

Removing classes with removeClass()

removeClass() removes 1 or more classes from an element or elements. The syntax is almost identical to addClass(). The only difference is that you can omit the class name argument — if you do this then all classes are removed from the element.

Here are some examples showing how to use removeClass():


// Remove the class 'summary' from #myDiv
$('#myDiv').removeClass('summary');

// Remove the classes 'header' and 'summary' from #myDiv
$('#myDiv').removeClass('header summary');

// Remove the class 'summary' from all divs in the page
$('div').removeClass('summary');

// Remove all classes from all divs in the page
$('div').removeClass();

// Callback example: Remove the class 'summary' from just the first 3 divs in the page
$('div').removeClass( firstThreeOnly );

function firstThreeOnly( index, classAttribute ) {
  return ( index < 3 ? 'summary' : '' );
}

Toggling classes with toggleClass()

toggleClass() lets you toggle a class for a given element or elements. In other words, if the element has the class then the class is removed from the element; if the element doesn't have the class then it is added.

In its most basic form, you call toggleClass() with the class name to toggle:


// Toggle the class 'summary' for the #myDiv element
$('#myDiv').toggleClass('summary');

// Toggle the class 'summary' for all divs
$('div').toggleClass('summary');

To toggle multiple classes, separate the class names with spaces:


// Toggle the classes 'header' and 'summary' for the #myDiv element
$('#myDiv').toggleClass('header summary');

You can also pass an override switch as the second argument to toggleClass():

  • If you pass true then toggleClass() always adds the class, just as if you'd called addClass().
  • If you pass false then toggleClass() always removes the class, just as if you'd called removeClass().

For example:


// Randomly add/remove the class 'summary' for the #myDiv element
$('#myDiv').toggleClass( 'summary', ( Math.random() < .5 ) );

This switch is handy if you want to toggle a class according to a more complex rule than simply: "Add the class if it's not there, or remove it if it is".

Finally, as with addClass() and removeClass(), you can pass a callback function instead of a class name in order to toggle a class based on an element's position, existing classes, or other properties. The callback function should accept 2 arguments:

  • The index position of the current element in the set (starting from zero)
  • The existing value of the class attribute (if any) for the current element

For example:


// Toggle the class 'summary' in just the first 3 divs in the page
$('div').toggleClass( firstThreeOnly );

function firstThreeOnly( index, classAttribute ) {
  return ( index < 3 ? 'summary' : '' );
}

Summary

In this tutorial you explored jQuery's methods for dealing with CSS classes:

  • hasClass() for checking if an element has a certain class
  • addClass() for adding a class to an element
  • removeClass() for removing a class from an element
  • toggleClass() for adding a class to an element if it doesn't already have it, or removing a class if it does

These methods make it really easy to manipulate element classes with just 1 or 2 lines of code. Such is the power of jQuery!

Until next time — have fun. :)

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page