• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / jQuery / Manipulating Element Classes with jQuery

Manipulating Element Classes with jQuery

12 May 2010 / Leave a Comment

Manipulating Element Classes with jQuery

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. 🙂

Filed Under: jQuery Tagged With: addClass, hasClass, javascript, jQuery, removeClass, toggleClass

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits