Home  »  CodeProgrammingSnippetsTechnology   »   How to Add a Class to an HTML Element Using Vanilla JavaScript

How to Add a Class to an HTML Element Using Vanilla JavaScript

Posted: August 3, 2022 | by Michael Bright

If you have an HTML element like this.

<div id="element"></div>

You can add or remove classes with similar JavaScript code.

var element = document.getElementById('element');
element.classList.add('class-1');
element.classList.add('class-2', 'class-3');

This would be the result.

<div id="element" class="class-1 class-2 class-3"></div>

Remove a class.

element.classList.remove('class-3');

This is after removing once of the classes.

<div id="element" class="class-1 class-2"></div>

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.