Adding a class to a JavaScript element is a common task that developers perform to apply custom styles or trigger animations on different HTML elements. In this blog post, we’ll learn how to add a class to a JavaScript element using the
classList property and the className property.
Method 1: Using the classList Property
The classList property is a read-only property that returns a live DOMTokenList collection of the class attributes of an element. You can use the add() method to add a class to an element.
Here’s an example of how to add a class to an element using the classList property:
<script> // Get the element by its ID const element = document.getElementById("myElement"); // Add a class to the element element.classList.add("myClass"); </script>
Method 2: Using the className Property
The className property sets or returns the class name of an element (the value of an element’s class attribute). You can use this property to add a class to an element by concatenating the new class name with the existing ones.
Here’s an example of how to add a class to an element using the className property:
<script> // Get the element by its ID const element = document.getElementById("myElement"); // Add a class to the element element.className += " myClass"; </script>
Note:
If the element already has a class name, you should add a space before the new class name to ensure there’s a separator between the class names.
Conclusion
In this blog post, we’ve learned how to add a class to a JavaScript element using the classList property and the className property. Both methods achieve the same goal, but the classList property provides a more straightforward and modern approach.