Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
communitycreator

What is the DOM `classList` property in HTML?

Ayush Trivedi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Overview

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.

Code

Let’s look at the following example and learn how to use the classList property to add a CSS class in the div element.

  • HTML

Code explanation

  • 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.

Output

We have successfully implemented the classList property. When we click the click me button, the background color of the div element will change.

RELATED TAGS

html
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring