Adding a class with javascript

You can add a class to an HTML element using JavaScript by using the classList property. The classList property provides methods for working with the classes of an element, including adding, removing, and checking for the presence of a class.

Here’s an example of how to add a class to an element using JavaScript:

<div id="example">This is an example element</div>

<script>
var element = document.getElementById("example");
element.classList.add("highlight");
</script>

In this example, we start by using the document.getElementById method to select the element with an id of example. We then access the classList property of the element, and use the add method to add a class of highlight to the element.

With this simple code, you can add a class to any HTML element in your document, allowing you to dynamically modify the styling of your page based on user interactions or other conditions.