Scripting CSS Classes

An alternative to scripting individual CSS styles through the inline style property is to script the value of the HTML class attribute. Changing an element’s class changes the set of stylesheet selectors that apply to the element and can cause multiple CSS properties to change at the same time. Suppose, for example, that you want a way to draw the user’s attention to individual paragraphs (or other elements) of a document. You might start by defining attention-grabbing styles for any elements that have a class name of “attention”:

.attention {  /* Styles to grab the user's attention */
    background-color: yellow;    /* Yellow highlight background */
    font-weight: bold;           /* Bold text */
    border: solid black 2px;     /* Black box */
}

The identifier class is a reserved word in JavaScript, so the HTML class attribute is available to JavaScript code using the name className. Here is code that sets and clears the className property of an element to add and remove the “attention” class for that element:

function grabAttention(e) { e.className = "attention"; }
function releaseAttention(e) { e.className = ""; }

HTML elements can be members of more than one CSS class and the class attribute holds a space-separated list of class names. The className property has a misleading name: classNames would have been a much better choice. The functions above assume that the className property will specify zero or one class name and do not work when more than one class is in use. If an element ...

Get JavaScript: The Definitive Guide, 6th Edition 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.