CoreUI ONE — 250+ PRO components and 25+ admin templates for React, Angular, Vue, Bootstrap and Next.js, plus Data Grid, Scheduler, 4,300+ PRO icons and the Next.js boilerplate. One license. → See what you get

How to add a class to an element in JavaScript

Adding CSS classes to elements dynamically enables interactive styling, state changes, and responsive design through JavaScript manipulation. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented dynamic class manipulation in countless interactive components for state management and visual feedback. From my expertise, the most effective approach is using the classList.add() method for clean and reliable class management. This method provides safe class addition without affecting existing classes and handles duplicate prevention automatically.

Use classList.add() method to safely add CSS classes to DOM elements.

// Get element and add class
let element = document.getElementById('my-element')
element.classList.add('active')

// Add multiple classes
element.classList.add('highlighted', 'animated', 'visible')

// Add class with conditional logic
let button = document.querySelector('.btn')
if (button) {
  button.classList.add('btn-primary')
}

// Add class to multiple elements
let cards = document.querySelectorAll('.card')
cards.forEach(card => {
  card.classList.add('shadow')
})

// Add class on event
document.getElementById('toggle-btn').addEventListener('click', () => {
  let sidebar = document.querySelector('.sidebar')
  sidebar.classList.add('open')
})

The classList.add() method adds the specified class to the element’s class list without removing existing classes. It automatically prevents duplicate classes and handles multiple class additions in a single call. Use querySelector or getElementById to target specific elements before adding classes.

Best Practice Note:

This is the same class manipulation approach we use in CoreUI JavaScript components for dynamic styling. Always check if elements exist before manipulating classes to prevent errors in your applications.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to get the last element in an array in JavaScript
How to get the last element in an array in JavaScript

How to compare dates with JavaScript
How to compare dates with JavaScript

How to disable a button in JavaScript
How to disable a button in JavaScript

How to check if a key exists in JavaScript object?
How to check if a key exists in JavaScript object?