Coder Perfect

How can I assign an element a class?

Problem

I have an element with a class already:

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

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:

element.classList.add("my-class");

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

element.classList.remove("my-class");

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" />
</div>

Then

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");
element.classList.add("otherclass");

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

element.classList.remove("otherclass");

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

Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")
YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")

Answered by davidcondrey

Solution #5

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

For adding class:

document.getElementById("div1").classList.add("classToBeAdded");

For removing class:

document.getElementById("div1").classList.remove("classToBeRemoved");

Answered by Shoaib Chikate

Post is based on https://stackoverflow.com/questions/507138/how-to-add-a-class-to-a-given-element