Skip to main content

Using className in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the className property in JavaScript to get or set the class attribute of an HTML element. We'll cover the basics of the className property and provide sample code with explanations.

What is className?

The className property is a built-in JavaScript DOM property that allows you to get or set the class attribute of an HTML element. You can use the className property to dynamically update your web page's content and styling by changing the class attribute of elements based on user interactions or other events.

Sample Code: Using className

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>className Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph" id="firstParagraph">This is an introductory paragraph.</p>
</div>
</body>
</html>

To use className to get or set the class attribute of an HTML element, you'll need to include a JavaScript <script> tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.

Here's how you can use the className property to get the class attribute of the p element with the ID firstParagraph and set it to a new value:

<!DOCTYPE html>
<html>
<head>
<title>className Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph" id="firstParagraph">This is an introductory paragraph.</p>
</div>

<script>
// Select the element with the ID "firstParagraph"
var firstParagraph = document.getElementById('firstParagraph');

// Use className to get the current class attribute value
var currentClass = firstParagraph.className;
console.log("The current 'class' attribute value is:", currentClass);

// Use className to set a new class attribute value
firstParagraph.className = 'newParagraphClass';
console.log("The updated 'class' attribute value is:", firstParagraph.className);
</script>
</body>
</html>

After running this code, the console will display:

The current 'class' attribute value is: mainParagraph
The updated 'class' attribute value is: newParagraphClass

The p element with the ID firstParagraph will now have a class attribute value of newParagraphClass.

Live Playground, Try it Yourself

Conclusion

The className property is a powerful tool for getting and setting the class attribute of HTML elements in the DOM. By mastering this property, you can dynamically update your web page's content and styling by changing the class attribute of elements based on user interactions or other events.