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:solidblack2px;/* 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:
functiongrabAttention(e){e.className="attention";}functionreleaseAttention(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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access