Replicate jQuery addClass in Vanilla JavaScript

Modern native JavaScript provides a built-in way to add classes to DOM elements without the overhead of jQuery. By using the standard classList API, developers can cleanly replicate the behavior of jQuery's .addClass() method for both single and multiple elements with zero dependencies and optimal performance.

Adding a Class to a Single Element

In jQuery, you target an element and call .addClass():

// jQuery
$('#myElement').addClass('active');

In modern vanilla JavaScript, you select the element using document.querySelector() (or document.getElementById()) and use the classList.add() method:

// Vanilla JavaScript
const element = document.querySelector('#myElement');
element.classList.add('active');

If the specified class already exists on the element, classList.add() automatically ignores it, preventing duplicate class names just like jQuery does.

Adding Multiple Classes

jQuery allows you to add multiple space-separated classes in a single string:

// jQuery
$('#myElement').addClass('active highlighted visible');

In native JavaScript, pass multiple class names as separate comma-delimited string arguments to classList.add():

// Vanilla JavaScript
const element = document.querySelector('#myElement');
element.classList.add('active', 'highlighted', 'visible');

Alternatively, if you have an array of class names, you can use the spread operator (...):

const classes = ['active', 'highlighted', 'visible'];
element.classList.add(...classes);

Adding a Class to Multiple Elements

A key feature of jQuery is implicit iteration: calling .addClass() on a selector containing multiple elements applies the change to all of them at once:

// jQuery
$('.items').addClass('selected');

Native JavaScript requires explicit iteration. Use document.querySelectorAll() to retrieve a NodeList and apply the forEach method:

// Vanilla JavaScript
const items = document.querySelectorAll('.items');

items.forEach((item) => {
  item.classList.add('selected');
});

Creating a Reusable Helper Function

To fully emulate jQuery's syntax and behavior across one or many elements, you can define a lightweight helper function:

function addClass(selector, ...classNames) {
  const elements = document.querySelectorAll(selector);
  elements.forEach((el) => el.classList.add(...classNames));
}

// Usage
addClass('.items', 'selected', 'active');

This approach replicates the functionality of jQuery's .addClass() natively while keeping your bundle size minimal and utilizing modern browser standards.