jQuery Manipulating element classes


Example

Assuming the page includes an HTML element like:

<p class="small-paragraph">
  This is a small <a href="https://en.wikipedia.org/wiki/Paragraph">paragraph</a>
  with a <a class="trusted" href="http://stackexchange.com">link</a> inside.
</p>

jQuery provides useful functions to manipulate DOM classes, most notably hasClass(), addClass(), removeClass() and toggleClass(). These functions directly modify the class attribute of the matched elements.

$('p').hasClass('small-paragraph'); // true
$('p').hasClass('large-paragraph'); // false

// Add a class to all links within paragraphs
$('p a').addClass('untrusted-link-in-paragraph');

// Remove the class from a.trusted
$('a.trusted.untrusted-link-in-paragraph')
.removeClass('untrusted-link-in-paragraph')
.addClass('trusted-link-in-paragraph');

Toggle a class

Given the example markup, we can add a class with our first .toggleClass():

$(".small-paragraph").toggleClass("pretty");

Now this would return true: $(".small-paragraph").hasClass("pretty")

toggleClass provides the same effect with less code as:

if($(".small-paragraph").hasClass("pretty")){
   $(".small-paragraph").removeClass("pretty");}
else {
   $(".small-paragraph").addClass("pretty"); }

toggle Two classes:

$(".small-paragraph").toggleClass("pretty cool");

Boolean to add/remove classes:

$(".small-paragraph").toggleClass("pretty",true); //cannot be truthy/falsey

$(".small-paragraph").toggleClass("pretty",false);

Function for class toggle (see example further down to avoid an issue)

$( "div.surface" ).toggleClass(function() {
  if ( $( this ).parent().is( ".water" ) ) {
    return "wet";
  } else {
    return "dry";
  }
});

Used in examples:

// functions to use in examples
function stringContains(myString, mySubString) {
  return myString.indexOf(mySubString) !== -1;
}
function isOdd(num) { return num % 2;}
var showClass = true; //we want to add the class

Examples:

Use the element index to toggle classes odd/even

$( "div.gridrow" ).toggleClass(function(index,oldClasses, false), showClass ) {
  showClass
  if ( isOdd(index) ) {
    return "wet";
  } else {
    return "dry";
  }
});

More complex toggleClass example, given a simple grid markup

<div class="grid">
  <div class="gridrow">row</div>
  <div class="gridrow">row</div>
  <div class="gridrow">row</div>
  <div class="gridrow">row</div>
  <div class="gridrow">row</div>
  <div class="gridrow gridfooter">row but I am footer!</div>
</div>

Simple functions for our examples:

function isOdd(num) {
  return num % 2;
}

function stringContains(myString, mySubString) {
  return myString.indexOf(mySubString) !== -1;
}
var showClass = true; //we want to add the class

Add an odd/even class to elements with a gridrow class

$("div.gridrow").toggleClass(function(index, oldClasses, showThisClass) {
  if (isOdd(index)) {
    return "odd";
  } else {
    return "even";
  }
  return oldClasses;
}, showClass);

If the row has a gridfooter class, remove the odd/even classes, keep the rest.

$("div.gridrow").toggleClass(function(index, oldClasses, showThisClass) {
  var isFooter = stringContains(oldClasses, "gridfooter");
  if (isFooter) {
    oldClasses = oldClasses.replace('even', ' ').replace('odd', ' ');
    $(this).toggleClass("even odd", false);
  }
  return oldClasses;
}, showClass);

The classes that get returned are what is effected. Here, if an element does not have a gridfooter, add a class for even/odd. This example illustrates the return of the OLD class list. If this else return oldClasses; is removed, only the new classes get added, thus the row with a gridfooter class would have all classes removed had we not returned those old ones - they would have been toggled (removed) otherwise.

$("div.gridrow").toggleClass(function(index, oldClasses, showThisClass) {
  var isFooter = stringContains(oldClasses, "gridfooter");
  if (!isFooter) {
    if (isOdd(index)) {
      return "oddLight";
    } else {
      return "evenLight";
    }
  } else return oldClasses;
}, showClass);