What is the HTML DOM property `className` in CSS?

Overview

In this shot, we will learn the HTML DOM property className, which returns the existing class of the element. When we assign it a new class, the existing class of the element will change to the newly assigned CSS class.

Code

Let’s try to change the existing class of a div element to a new class.

Explanation

  • In lines 5-6, we have a CSS class, new, for which we have defined the property background-color as red.

  • In lines 7-8, we have another CSS class, old, for which we have defined the property background-color as yellow. This is the current class of the div element.

  • In line 15, we insert a paragraph tag for displaying text.

  • In line 17, we insert a div element, having an ID and class as attributes, which we will use to get/select the element.

  • In line 21, we have a button tag that has its function bound with an onclick event.

  • In line 24, in script tag, we define a function change(), which will be called when we press the button from the HTML page.

  • In line 25, we use the document.getElementById() to get the desired element of DOM. We then apply .className, which will return exisisting class and we are assigning a new class.

Output

We have successfully implemented the className property. When we click the “Click me” button, the CSS class of the div element is changed from old to new.

Free Resources