Add Classes To An Element - JavaScript Tutorial

Skip to content

Home » Add a Class to an Element

To add a class to an element, you use the classList property of the element. Suppose you have an element as follows:

<div>Item</div>Code language: HTML, XML (xml)

To add the box class to the <div> element, you use the following:

const div = document.querySelector('div'); div.classList.add('box');Code language: JavaScript (javascript)

It’s possible to add multiple classes. The following adds three classes to the <div> element:

const div = document.querySelector('div'); div.classList.add('box','primary','rounded');Code language: JavaScript (javascript)Send Cancel Get Width and Height of an ElementPreviouslyGet Width and Height of an Element Up NextRemove a Class from an Element Remove a Class from an Element Search for:

Getting Started

JavaScript Fundamentals

JavaScript Operators

Control Flow

JavaScript Functions

JavaScript Objects

Classes

Advanced Functions

Promises & Async/Await

JavaScript Modules

Javascript Error Handling

JavaScript Runtime

Primitive Wrapper Types

More JavaScript Operators

Tag » Add Class To Dom Element Js