Manipulating Classes
On of the most common changes made to an HTML Element by JavaScript is adding, removing and toggling classes. Because this is so common, JavaScript has a special class object and a set of methods specifically for HTML Element class manipulations. Using the classList
object of an HTML Element, we can add()
, remove()
and toggle()
classes.
Adding Classes
To add a class to an HTML Element, we can use the classList.add()
function. It is possible to add more than one class at a time by separating them by a comma.
$link.classList.add('btn', 'btn-primary')
Removing Classes
To remove a class from an HTML Element, we can use the classList.remove()
function. It is possible to remove more than one class at a time by separating them by a comma.
$link.classList.remove('btn', 'btn-primary')
Toggling Classes
To remove a class form an HTML Element if it is present or to add a class if it is not, we can use the classList.toggle()
function. It is NOT possible to toggle more than one class with a single function call.
$link.classList.toggle('active')