56

Suppose a HTML element's id is known, so the element can be refereced using:

document.getElementById(element_id);

Does a native Javascript function exist that can be used to append a CSS class to that element?

7 Answers 7

96
var element = document.getElementById(element_id);
element.className += " " + newClassName;

Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).

Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.

In prototype, for instance:

// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);

See how much nicer that is?!

Sign up to request clarification or add additional context in comments.

7 Comments

If all the op needs to do is add a class, I wouldn't advise downloading an entire javascript framework for this purpose. Would be rather bloated, no?
@Elijah - there is also a cost associated with writing messy, less-readable javascript, which gets pretty unwieldy after about 15 lines of code. jquery is ~50k compressed - I think it's worth it pretty early on.
@Triptych. Agreed on readability. And if you use the Google hosted version of the library, it may very well already be cached on the user's machine, thus possibly even saving time.
Triptych, there's no need for a library. If the OP so desires then he/she can create a suitable abstraction.
@J-P There's also no reason to assume that the OP is only using Javascript to change the class of a single element. In any case, I gave both answers; if the OP sees the need, he can make an informed decision.
|
36

Adding class using element's classList property:

element.classList.add('my-class-name');

Removing:

element.classList.remove('my-class-name');

Comments

11

classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.

Not supported in IE < 10

Comments

3

When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.

Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

document.addClass= function(el, css){
    var tem, C= el.className.split(/\s+/), A=[];    
    while(C.length){
        tem= C.shift();
        if(tem && tem!= css) A[A.length]= tem;
    }
    A[A.length]= css;
    return el.className= A.join(' ');   
}

Comments

1

You should be able to set the className property of the element. You could do a += to append it.

Comments

0
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));

This will add ONE class or MULTIPLE classes :

addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"

Comments

-1

you could use setAttribute.

Example: For adding one class:

 document.getElementById('main').setAttribute("class","classOne"); 

For multiple classes:

 document.getElementById('main').setAttribute("class", "classOne classTwo"); 

1 Comment

setAttribute doesn't append a class - it sets the list of classes, so any existing classes are lost

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.