Java Reference
In-Depth Information
Classes of an Element
The
className
Property
As we've seen, we can modify the class name of an element using the
setAttribute()
method. There is also a
className
property that allows the class of an element to be set
directly. In addition, it can be used to find out the value of the class attribute:
swim.className;
<< "swimming"
We can change the class back to
swim
with the following code:
swim.className = "swim"
<< "swim"
The
classList
Property
The
classList
property is a list of all the classes an element has. It has a number of
methods that make it easier to modify the class of an element. It's supported in all modern
browsers and in Internet Explorer from version 10 onwards.
The
add
method works in a similar way to the
addClass
function we created above, and
can be used to add a class to an element. For example, we could add a class of "sport" to the
run
element:
run.classList.add('run');
<< undefined
The
remove
method will remove a specific class from an element. For example, we could
remove the class of "swim" from the
swim
element:
swim.classList.remove('swim');
<< undefined
