Working With CSS Classes JQ Home  <<  JQ Basics  <<  Working With CSS Classes

In this lesson we take our first look at the close interaction between jQuery and CSS by looking at how we can work with CSS classes when using jQuery.

The jQuery methods in this section allow us to add, remove and toggle classes off and on as well as checking for the existence of a particular class on the page. This gives us complete control of the CSS classes on our page allowing a great deal of flexibility when using the class attribute.

CSS Class Methods Description
.addClass()Add the specified class(es) to each element of the matched set.
.hasClass()Determine whether the specified class is assigned to any elements within the matched set.
.removeClass()Remove the specified class(es) or all classes from each element of the matched set.
.toggleClass()Add or remove the specified class(es) from each element of the matched set.

The .addClass() Method Top

Add the specified class(es) to each element of the matched set.

We will be using the .addClass( className ) signature for our example which adds one or more classes to each element within the matched set.

The second signature .addClass( classNames ) will add an array of classes to each element within the matched set.

The third signature .addClass( function(index, currentClass) ) will execute a function that returns one or more classes to be added to each element within the matched set

Examples of all three signatures are available in the reference section.

In the example below when we press the left button we select all odd 'td' elements within the table and add the class 'turnOrange' detailed below. Please note these changes are only visible if this button is pressed first. CSS always applies styles top-down so even though we may append 'turnOrange' to 'turnOlive', if both are present 'turnOlive' will be used as it is the last style in the CSS styles list.

When we press the right button we select all odd 'td' elements within the table, remove the class 'turnOrange' and add the class 'turnOlive' detailed below.


.turnOrange {
  background-color: orange;
}
.turnOlive {
  background-color: olive;
}

Table For Testing The .addClass( className ) Method
Table Row 1, Table Data 1 Table Row 1, Table Data 2
Table Row 2, Table Data 1 Table Row 2, Table Data 2
Table Row 3, Table Data 1 Table Row 3, Table Data 2
Table Row 4, Table Data 1 Table Row 4, Table Data 2


$(function(){
  $('#btn1').on('click', function() {
    $('.testtable td:odd').addClass('turnOrange'); // only works if clicked first
  });
  $('#btn2').on('click', function() {
    $('.testtable td:odd').removeClass('turnOrange') 
                          .addClass('turnOlive'); 
  });
});

Press the button below to action the above code:

             

The .hasClass() Method Top

Determine whether the specified class is assigned to any elements within the matched set.

  • Returns true if any of the classes for the element match the specified class.

The .hasClass() method, has one signature .hasClass( className ) which returns true if any of the classes for the element match the specified class.

In the example below when we press the button we iterate over all 'td' elements within the table and turn the background colour to orange if they contain a class 'turnAqua' .

Table For Testing The .hasClass( className ) Method
Table Row 1, Table Data 1  (class of turnAqua) Table Row 1, Table Data 2
Table Row 2, Table Data 1  (class of turnAqua) Table Row 2, Table Data 2  (class of turnAqua)
Table Row 3, Table Data 1  (class of turnAqua) Table Row 3, Table Data 2
Table Row 4, Table Data 1 Table Row 4, Table Data 2  (class of turnAqua)


$(function(){
  $('#btn3').on('click', function() {
    $('.testtable2 td').each(function (index, tableElement) { 
       if ($(this).hasClass('turnAqua')) {
           $(this).css('backgroundColor', 'orange');
       };
    });
  });
});

Press the button below to action the above code:

The .removeClass() Method Top

Remove the specified class(es) or all classes from each element of the matched set.

  • Often used in tandem with the .addClass() method to switch class styling.

We will be using the .removeClass( function(index, currentClass) ) signature, which returns a function of one or more classes to be removed from each element within the matched set.

The second signature .removeClass() removes all classes from each element within the matched set.

The third signature .removeClass( className ) removes one or more classes from each element within the matched set.

The fourth signature .removeClass( classNames ) removes an array of classes from each element within the matched set.

Examples of all these signatures are available in the reference section.

In the example below when we press the button we select all 'td' elements within the table with an id of 'testtable3'. We then iterate over the collection removing any class that is 'turnYellow' etc. We end up with all rows returned to a colour of orange.


.turnAqua {
  background-color: aqua;
}
.turnOlive {
  background-color: olive;
}
.turnSilver {
  background-color: silver;
}
.turnYellow {
  background-color: yellow;
}

Table For Testing The .removeClass( function(index, currentClass) ) Method
Table Row 1, Table Data 1  (class of turnYellow) Table Row 2, Table Data 1  (class of turnSilver)
Table Row 2, Table Data 1 Table Row 2, Table Data 2  (class of turnAqua)
Table Row 3, Table Data 1  (class of turnYellow) Table Row 3, Table Data 1  (class of turnAqua)
Table Row 4, Table Data 1 Table Row 4, Table Data 2  (class of turnOlive)


$(function(){
  $('#btn4').on('click', function() {
    $('.testtable3 td').removeClass( function( index, currentClass ) {
      var loseClass;
      if ( currentClass === 'turnYellow' ) {
    	  loseClass = 'turnYellow';
      } else if ( currentClass === 'turnSilver' ) {
    	  loseClass = 'turnSilver';
      } else if ( currentClass === 'turnAqua' ) {
    	  loseClass = 'turnAqua';
      } else {
    	  loseClass = 'turnOlive';
      }
      return loseClass;
    });
  });
});

Press the button below to action the above code:

The .toggleClass() Method Top

Add or remove the specified class(es) from each element of the matched set.

The first signature .toggleClass( [, switch ] ) was deprecated in jQuery 3.0 and removes all classes from each element within the matched set optionally filtered with a boolean switch.

We will be using the second signature .toggleClass className [, switch ] ) signature for our example, which toggles one or more classes for each element within the matched set optionally filtered with a boolean switch.

The third signature .toggleClass classNames [, switch ] ) toggles an array of one or more classes for each element within the matched set optionally filtered with a boolean switch.

The fourth signature .toggleClass( function(index, class [, switch] ) will execute a function that returns one or more classes to be toggled from each element within the matched set optionally filtered with a boolean switch.

Examples of all these signatures are available in the reference section.

In the example below when we press the left button we toggle the 'turnAqua' class on and off to change table data in the table below to aqua or revert them to their original colour.

When we press the right button we check the table to see if the 'turnAqua' class exists and if so we toggle it off using a JavaScript Boolean object as the second parameter. If the 'turnAqua' class doesn't exist we toggle it on using a JavaScript Boolean object as the second parameter.


.turnAqua {
  background-color: aqua;
}

Table For Testing The .toggleClass( className [, switch ] ) Signature
Table Row 1, Table Data 1 Table Row 1, Table Data 2
Table Row 2, Table Data 1 Table Row 2, Table Data 2


$(function(){
  $('#btn5').on('click', function() {
    $('.testtable4').toggleClass('turnAqua'); 
  });
  $('#btn6').on('click', function() {
    trueBoolean = new Boolean(true);
    var aBoolean = false;
    $('.testtable4 tr').each(function (index, tableElement) { 
      if ($(this).hasClass('turnAqua')) { 
        aBoolean = true;
      };
    });
    if (aBoolean) {
        alert('We are toggling the turnAqua class off');
        $('.testtable4 tr').toggleClass('turnAqua', trueBoolean);
    } else {
        alert('We are toggling the turnAqua class on');
        $('.testtable4 tr').toggleClass('turnAqua', trueBoolean);
    };
  });
});

Press the button below to action the above code:

          

In this lesson we looked at the jQuery Class Attribute methods.

Related Tutorials

jQuery Basics - Lesson 9: Working With CSS Attributes
jQuery Basics - Lesson 10: Working With General CSS Properties
jQuery Basics - Lesson 11: Working With Dimension & Position CSS Properties

Reference

Methods

Attributes & Properties - .addClass() method
Attributes and Properties - .css() method
Attributes & Properties - .hasClass() method
Attributes & Properties - .removeClass() method
Attributes & Properties - .toggleClass() method
Events - .on() method
jQuery Selectors - :odd selector
Other Traversal - .each() method