How do I add a CSS class to an element using JavaScript?
Benjamin C
benjamin c profile pic

To add a CSS class to an element using JavaScript, you can utilize theclassList property and its methods provided by the DOM API. Here's a step-by-step guide on how to achieve this: 1. Get a reference to the element you want to add the CSS class to:

1
2
3

   const element = document.getElementById('myElement');
   

Replace'myElement' with the appropriate identifier or selector for your target element. 2. Use theclassList.add() method: TheclassList property of an element provides methods to manipulate the classes of the element. Theadd() method adds one or more CSS classes to the element.

1
2
3

   element.classList.add('myClass');
   

In this example, the CSS class'myClass' will be added to the element. 3. Add multiple classes: To add multiple CSS classes in one go, you can pass multiple arguments to theadd() method:

1
2
3

   element.classList.add('class1', 'class2', 'class3');
   

This will add multiple classes to the element. 4. Check for existing classes before adding: If you want to avoid adding a class that already exists on the element, you can use thecontains() method to check if the class is already present:

1
2
3
4
5

   if (!element.classList.contains('myClass')) {
     element.classList.add('myClass');
   }
   

This will prevent adding the class if it is already present on the element. By following these steps, you can add a CSS class to an element using JavaScript. TheclassList property and itsadd() method provide a convenient way to manipulate CSS classes on elements.