Sometimes you need to add or remove a CSS class with JavaScript, and you don't want to include an entire library like jQuery to do it.
This is useful in situations when you want your page elements to change in response to user actions.
Example uses include:
- Showing or hiding a menu
- Highlighting a form error
- Showing a dialog box
- Showing different content in response to a selection
- Animating an element in response to a click
There are two JavaScript properties that let you work with classes: className
and classList
. The former is widely compatible, while the latter is more modern and convenient. If you don't need to support IE 8 and 9, you can skip className
.
We'll start with the compatible version first.
Note: This tutorial assumes some familiarity with JavaScript concepts like functions and variables.
Modifying Classes the Compatible Way
The JavaScript className
property lets you access the class
attribute of an HTML element. Some string manipulation will let us add and remove classes.
We'll access HTML elements using querySelectorAll()
, which is compatible with browsers from IE8 and up.
Add a Class
To add a class, we'll write a function that takes in the elements we want to change and adds a specified class to all of them.
function addClass(elements, myClass) {
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have only one dom element, make it an array to simplify behavior
else if (!elements.length) { elements=[elements]; }
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
if (!(' '+elements[i].className+' ').indexOf(' '+myClass+' ') > -1) {
elements[i].className += ' ' + myClass;
}
}
}
You'll see how the function works soon, but to watch the function in action, feel free to use this CSS:
.red{
background: red;
}
.highlight{
background: gold;
}
...and this HTML:
Continue reading %Quick Tip: Add or Remove a CSS Class with Vanilla JavaScript%
by Yaphi Berhanu via SitePoint
No comments:
Post a Comment