Add class to HTML element

JavaScript, Browser · Dec 30, 2020

Adds a class to an HTML element.

  • Use Element.classList and DOMTokenList.add() to add the specified class to the element.
const addClass = (el, className) => el.classList.add(className);
addClass(document.querySelector('p'), 'special');
// The paragraph will now have the 'special' class

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this