How to Add a Class to an Element

A quick guide on how to add a CSS class to an HTML element in TypeScript using the classList.add() method.

To dynamically change the style of an element, a common way is to add a CSS class to it. The classList property on an element makes this very simple.

Let’s say you have a special class that adds a highlight style, and you want to apply it to an element.

HTML
<div id="my-element">
    <p>Some content</p>
</div>

<style>
    .highlight {
        background-color: yellow;
        border: 1px solid orange;
    }
</style>

To apply the highlight, you can select the element and then use the classList.add() method.

TypeScript
const myElement = document.querySelector<HTMLDivElement>("#my-element");

if (myElement) {
    // Add the 'highlight' class
    myElement.classList.add("highlight");
}

After this code runs, the <div> will get the yellow background and orange border from the .highlight class.

How it works:

  1. myElement.classList: This property gives you access to the element’s list of classes as a special object with helpful methods.
  2. .add("highlight"): This is a method on classList that adds the “highlight” class to the element. If the class is already on the element, it won’t be added again, and it won’t cause an error.

You can also add multiple classes at once by passing more arguments:

TypeScript
myElement.classList.add("class1", "class2");

Other recipes in DOM