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 limit items in a .map loop in JavaScript
How to limit items in a .map loop in JavaScript

How to validate an email address in JavaScript
How to validate an email address in JavaScript

What is the Difference Between Null and Undefined in JavaScript
What is the Difference Between Null and Undefined in JavaScript

How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

Answers by CoreUI Core Team