Categories
JavaScript Answers

How to add class to HTML element with JavaScript?

Spread the love

You can add a class to an HTML element using JavaScript by accessing the element using its ID, class, tag name, or any other suitable selector, and then using the classList property to manipulate its classes.

For example we write:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Add Class with JavaScript</title>
  <style>
    .highlight {
      background-color: yellow;
    }
  </style>
</head>
<body>

  <p id="paragraph">This is a paragraph.</p>

  <script>
    // Select the element by ID
    var paragraph = document.getElementById("paragraph");

    // Add a class to the element
    paragraph.classList.add("highlight");
  </script>

</body>
</html>

In this example, the JavaScript code selects the <p> element with the ID “paragraph” and adds the class “highlight” to it.

As a result, the background color of the paragraph will change to yellow according to the CSS defined for the “highlight” class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *