Chapter 8: DOM element Properties

8.2 className

Next, let’s look at the className property. This property allows us to change the class name of an element. For instance, add the following line to chap8.js to change the class name of the second <div> element:

document.getElementById("second").className = "myclass";

You can verify that the class name of the second <div> has indeed been changed by adding

console.log(document.getElementById("second").className);

to chap8.js. You’ll get

myclass

as the output in the console window when you run the code.

The ability to change class names is very useful if we want to change the CSS style of a group of elements in Javascript. We can do that by assigning a class to each of them in Javascript and style that class in CSS. We’ll learn how to do that in our project later.