Logo - Albert Walicki

How to change element's class with Javascript?

Short cheatsheet for adding, removing, and toggling CSS classes in vanilla javascript. You no longer have to remember it!

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:


Remove class

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


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:


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) => {

See more solutions!


How to Disable the Resize of the <textarea> HTML Element?

To disable resizing of textarea, we need to set only one CSS property.


Extra space below image

One of the most common problems that almost every junior frontend developer has is extra space below the image. Let's learn how to fix it with CSS

Logo - Albert Walicki

Hello, I'm a frontend developer with over six years of experience, freelancer. I'm also a mentor for junior frontend developers. 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