Coder Perfect

How can I assign an element a class?


I have an element with a class already:

<div class="someclass">
    <img ... id="image1" name="image1" />

Now I’d like to write a JavaScript function that adds a class to the div element (not replace, but add).

I’m not sure how I’m going to accomplish it.

Asked by Blankman

Solution #1

To add a class, use element.classList.add:


To delete a class, use element.classList.remove:


To the element’s className property, add a space and the name of your new class. First, give the element an id so you can quickly reference it.

<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />


var d = document.getElementById("div1");
d.className += " otherclass";

It’s worth noting that otherclass is preceded by a space. It’s critical to include the space; else, existing classes in the class list will be jeopardized.

On MDN, look up element.className.

Answered by Ishmael

Solution #2

The element.classList.add method is the simplest way to achieve this without a framework.

var element = document.getElementById("div1");

Edit: If you want to delete a class from an element, use the following code.


I like not to have to fill in any blanks or deal with duplicate entries (which is required when using the document.className approach). There are some browser limits, but polyfills can help you get around them.

Answered by Yuri

Solution #3

Find your target element “d” in whichever way you like, and then do the following:

d.className += ' additionalClass'; //note the space

You can wrap that in more smart ways to check for pre-existence and space needs, for example.

Answered by annakata

Solution #4


Answered by davidcondrey

Solution #5

Another way to add a class to an element is to use pure JavaScript.

For adding class:


For removing class:


Answered by Shoaib Chikate

Post is based on