In this shot, we will learn about the HTML DOM classList
property, which is used to return all of the subclasses that an element contains.
We can also use the HTML DOM classList
property to dynamically add or remove CSS classes inside an element.
Let’s look at the following example and learn how to use the classList
property to add a CSS class in the div
element.
In line 5, we have CSS code for the class coloring
. This is where we define the background-color
property as yellow
.
In line 12, we have a paragraph tag to display text.
In line 14, we have a button
tag. This button
tag has a function, change
, which is bound on the onClick
event.
In line 16, we have a div
element with ID add
. This is the point where the coloring
class will be added as the subclass.
In line 21, inside the script tag, we have the JavaScript code where we define a change()
function. This function is called, as the onClick
event gets triggered. We use document.getElementById()
to get the desired element of DOM. Then, we apply the .classList
property, which returns all the subclasses in the desired element. Lastly, we use the .add
function of the .classList
property to apply the styling defined in the coloring
class.
We have successfully implemented the classList
property. When we click the click me
button, the background color of the div
element will change.