jel04h
2/12/2017 - 4:38 AM

Getting and Setting CSS Classes: Recall that the value of the class attribute (accessed via the className property in JavaScript) is interp

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: From https://www.safaribooksonline.com/library/view/jquery-pocket-reference/9781449398958/ch02s03.html

// 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) {      
    return "big bold h1-" + n;
});
$("h1").toggleClass("hilite", true);  // Like addClass
$("h1").toggleClass("hilite", false); // Like removeClass

// Testing for CSS classes: does any <p> have this class?
$("p").hasClass("firstpara")           
// This does the same thing.
$("#lead").is(".firstpara")            
// is() is more flexible than hasClass()
$("#lead").is(".firstpara.hilite")     


// Note that the hasClass() method is less flexible than addClass(), removeClass(), and toggleClass(). hasClass() works for only a single class name and does not support function arguments. It returns true if any of the selected elements has the specified CSS class, and it returns false if none of them does. The is() method (described in Queries and Query Results) is more flexible and can be used for the same purpose.
// These jQuery methods are like the methods of the HTML5 classList property. But the jQuery methods work in all browsers, not just those that support HTML5. Also, of course, the jQuery methods work for multiple elements and can be chained.