in JS by (16.3k points)
0 like 0 dislike
399 views

How I can to add a CSS class to a given element in JavaScript?

I have an element that already has a CSS class. Now I want add a other CSS class to this element (not replace, but add). How can I do that?


js add class
append css class on javascript

6 Answers

0 like 0 dislike
by (16.3k points)

Modern browsers solution

If you're only targeting modern browsers, then use element.classList.add method to add a class:

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

And use element.classList.remove method to remove a class:

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

Old browsers solution

If you need to support Internet Explorer 9 or lower, then add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id="foo" class="some-class">
    <img ... id="image1" name="image1" />
</div>

Then

var el = document.getElementById("foo");
el.className += " other-class";

Note the space before other-class. It's important to include the space otherwise it compromises existing classes that come before it in the class list.

See also element.className on MDN.

0 like 0 dislike
by (16.3k points)

Add Class

  • Cross Compatible

    In the following example we add a classname to the <body> element. This is IE-8 compatible.

    var a = document.body;
    a.classList ? a.classList.add('classname') : a.className += ' classname';
    

    This is shorthand for the following..

    var a = document.body;
    if (a.classList) {
        a.classList.add('wait');
    } else {
        a.className += ' wait';
    }
    

  • Performance

    If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.

    var z = document.body;
    document.body.classList.add('wait');
    

  • Convenience

    Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf

    $('body').addClass('wait');
    


Removing the class

  • Performance

    Using jQuery selectively is the best method for removing a class if your concerned with performance

    var a = document.body, c = ' classname';
    $(a).removeClass(c);
    

  • Without jQuery it's 32% slower

    var a = document.body, c = ' classname';
    a.className = a.className.replace( c, '' );
    a.className = a.className + c;
    

Using Prototype

Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")

Using YUI

YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")
0 like 0 dislike
by (16.3k points)

In modern JS you can convenient add class to element using only pure JavaScript.

Adding class:

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

Removing class:

document.getElementById("bar").classList.remove("classToBeRemoved");
0 like 0 dislike
by (16.3k points)

On old browsers with support old JS verison You can use these two functions:

function addClass(classname, element) {
    var cn = element.className;
    // test for existance
    if (cn.indexOf(classname) != -1) {
        return;
    }
    // add a space if the element already has class
    if (cn != '') {
        classname = ' ' + classname;
    }
    element.className = cn + classname;
}

function removeClass(classname, element) {
    var cn = element.className;
    var rxp = new RegExp("\\s?\\b"+classname+"\\b", "g");
    cn = cn.replace(rxp, '');
    element.className = cn;
}
0 like 0 dislike
by (16.3k points)

Assuming you're doing more than just adding this one class (eg, you've got asynchronous requests and so on going on as well), I'd recommend a library like Prototype or jQuery.

This will make just about everything you'll need to do (including this) very simple.

So let's say you've got jQuery on your page now, you could use code like this to add a class name to an element (on load, in this case):

$(document).ready(function() {
  $('#div1').addClass('some_other_class');
});

Check out the jQuery API browser for other stuff.

0 like 0 dislike
by (16.3k points)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

Please log in or register to answer this question.