When working with JavaScript, there may be situations where you need to dynamically add a class to elements that already have manual class names assigned to them. This can be useful when you want to apply additional styling or functionality to specific elements based on certain conditions.
Fortunately, there are multiple ways to achieve this. Let’s explore two common solutions.
Solution 1: Using the classList API
The classList API provides a convenient way to manipulate classes on an element. To dynamically add a class to an element with manual class names, you can use the add()
method of the classList
property.
const element = document.getElementById('myElement');
element.classList.add('newClass');
In the code snippet above, we first retrieve the element with the specified ID using the getElementById()
method. Then, we use the classList.add()
method to add the class newClass
to the element.
Solution 2: Manipulating the className property
Another way to dynamically add a class to an element with manual class names is by manipulating the className
property of the element. This property contains a string representing all the class names assigned to the element.
const element = document.getElementById('myElement');
element.className += ' newClass';
In the code snippet above, we retrieve the element with the specified ID and then concatenate the class name newClass
to the existing className
property using the +=
operator.
Both solutions achieve the same result of dynamically adding a class to an element with manual class names. Choose the solution that best fits your specific use case and coding style.
Here’s an example of how the final HTML markup might look like:
This is a sample element
Leave a Reply