0
0
JavascriptHow-ToBeginner · 3 min read

How to Add a Class in JavaScript: Simple Syntax and Examples

To add a class to an HTML element in JavaScript, use the element.classList.add('className') method. This adds the specified class without removing existing classes.
📐

Syntax

The syntax to add a class to an element is simple:

  • element: The HTML element you want to modify.
  • classList: A property that holds the list of classes on the element.
  • add('className'): A method that adds the specified class to the element.
javascript
element.classList.add('className');
💻

Example

This example shows how to add a class named highlight to a paragraph element when a button is clicked.

javascript
const paragraph = document.querySelector('p');
const button = document.querySelector('button');

button.addEventListener('click', () => {
  paragraph.classList.add('highlight');
  console.log('Class added:', paragraph.className);
});
Output
Class added: highlight
⚠️

Common Pitfalls

Common mistakes when adding classes include:

  • Using element.className = 'className' which replaces all existing classes instead of adding.
  • Trying to add a class to a null or undefined element (e.g., if the selector doesn't find anything).
  • Forgetting to use quotes around the class name.
javascript
/* Wrong: replaces all classes */
element.className = 'newClass';

/* Right: adds a class without removing others */
element.classList.add('newClass');
📊

Quick Reference

Here is a quick summary of useful classList methods:

MethodDescription
add('className')Adds the specified class to the element.
remove('className')Removes the specified class from the element.
toggle('className')Adds the class if missing, removes if present.
contains('className')Returns true if the element has the class.

Key Takeaways

Use element.classList.add('className') to add a class without removing existing ones.
Avoid using element.className = 'className' if you want to keep other classes.
Always ensure the element exists before adding a class to avoid errors.
classList provides useful methods like add, remove, toggle, and contains for class management.