Logo - Albert Walicki
JAVASCRIPT

How to change element's class with Javascript?

Short cheatsheet for adding, removing and toggling css classes

To add, remove or toggle element's class, first of all, we need to get this element. The most modern way is to use document.querySelector. Javascript have element.classList property, which will return DOMTokenList collection attributes of the element. And that's how we can manipulate elements classes.


Add new class

To add new class, we need to use .add() method:

document.querySelector(".someClass").classList.add('newClass');

Remove class

To remove class from element, we need to use .remove() method:

document.querySelector(".someClass").classList.remove('newClass');

Toggle class

Lastly, to toggle class (remove, if class exist and add if the class doesn't exist), we need to use the .toggle() method:

document.querySelector(".someClass").classList.toggle('newClass');

Add class to multiple elements at once

But what if we want to add specific class to all existing classes? We need to use different selector - document.querySelectorAll, which will return a list of elements with class from parameter. Then, to add, remove or toggle class, we should use .forEach() method.

document.querySelectorAll(".someClass").forEach((el) => {
    el.classList.add('newClass');
});

See more solutions!

HTML

How to create a tooltip in HTML and CSS?

Two easy ways to create tooltip, without javascript.

CSS

Extra space below image

One of the most common problems that almost every junior frontend developer had

Logo - Albert Walicki

Hello, i’m Albert Walicki. i’m a frontend developer and cofounder of development & design agency Hype4 and education platform Hype4 Academy. I wrote a book for Junior Frontend developers called Frontend Unicorn.

BlogGlassmorphismAurora UIShapes in CSSUnique css illustrations

Get in touch!

Have a question or need a project? Contact me!

© 2020-present Albert Walicki. All Rights Reserved