How to add class to element in Javascript

By FoxLearn 12/18/2024 4:23:49 AM   26
In JavaScript, you can add a class to an HTML element using the classList property and the add() method.

This method adds the specified class to the element without affecting any existing classes.

document.getElementById("myElement").classList.add("myClass")

This code selects the element with the ID "myElement" and adds the class "myClass" to its classList.

How to add a class to a html element in javaScript?

For example, Add a class to an element by its id:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Add Class Example</title>
</head>
<body>
  <div id="myElement">Javascript add class to element</div>
  <button onclick="addClassToElement()">Add Class</button>
  <script>
    function addClassToElement() {
      // Get the element by its ID
      var element = document.getElementById('myElement');
      // Add the 'new-class' to the element's class list
      element.classList.add('new-class');
    }
  </script>
</body>
</html>

For example, Add a class to an element by its class name or other selector

// Add class to all elements with a certain class name
document.querySelectorAll('.some-class').forEach(function(element) {
  element.classList.add('new-class');
});

classList.add('className') adds a new class without removing any existing classes.

If the class is already present on the element, it won't be added again. You can also add multiple classes at once: element.classList.add('class1', 'class2');.