2 * CSSClass.js: utilities for manipulating the CSS class of an HTML element.
4 * This module defines a single global symbol named CSSClass. This object
5 * contains utility functions for working with the class attribute (className
6 * property) of HTML elements. All functions take two arguments: the element
7 * e being tested or manipulated and the CSS class c that is to be tested,
8 * added, or removed. If element e is a string, it is taken as an element
9 * id and passed to document.getElementById().
11 var CSSClass = {}; // Create our namespace object
13 // Return true if element e is a member of the class c; false otherwise
14 CSSClass.is = function(e, c) {
15 if (typeof e == "string") e = document.getElementById(e); // element id
17 // Before doing a regexp search, optimize for a couple of common cases.
18 var classes = e.className;
19 if (!classes) return false; // Not a member of any classes
20 if (classes == c) return true; // Member of just this one class
22 // Otherwise, use a regular expression to search for c as a word by itself
23 // \b in a regular expression requires a match at a word boundary.
24 return e.className.search("\\b" + c + "\\b") != -1;
27 // Add class c to the className of element e if it is not already there.
28 CSSClass.add = function(e, c) {
29 if (typeof e == "string") e = document.getElementById(e); // element id
30 if (CSSClass.is(e, c)) return; // If already a member, do nothing
31 if (e.className) c = " " + c; // Whitespace separator, if needed
32 e.className += c; // Append the new class to the end
35 // Remove all occurrences (if any) of class c from the className of element e
36 CSSClass.remove = function(e, c) {
37 if (typeof e == "string") e = document.getElementById(e); // element id
38 // Search the className for all occurrences of c and replace with "".
39 // \s* matches any number of whitespace characters.
40 // "g" makes the regular expression match any number of occurrences
41 e.className = e.className.replace(new RegExp("\\b"+ c+"\\b\\s*", "g"), "");