Getting and Setting CSS Classes

Recall that the value of the class attribute (accessed via the className property in JavaScript) is interpreted as a space-separated list of CSS class names. Usually, we want to add, remove, or test for the presence of a single name in the list rather than replace one list of classes with another. For this reason, jQuery defines convenience methods for working with the class attribute. addClass() and removeClass() add and remove classes from the selected elements. toggleClass() adds classes to elements that don’t already have them, and removes classes from those that do. hasClass() tests for the presence of a specified class. Here are some examples:

// Add a CSS class to all <h1> tags $("h1").addClass("hilite"); // Add 2 classes to <p> tags after <h1> $("h1+p").addClass("hilite firstpara"); // Pass a function to add a computed class to each elt. $("section").addClass(function(n) { return "section" + n; }); // Remove a class from all <p> tags $("p").removeClass("hilite"); // Multiple classes are allowed $("p").removeClass("hilite firstpara"); // Remove computed classes from tags $("section").removeClass(function(n) { return "section" + n; }); // Remove all classes from all <div>s $("div").removeClass(); // Toggle a CSS class: add the class if it is not // there or remove it if it is. $("tr:odd").toggleClass("oddrow"); // Toggle two classes at once $("h1").toggleClass("big bold"); // Toggle a computed class or classes $("h1").toggleClass(function(n) ...

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.