Categories
dom html javascript

How can I change an element’s class with JavaScript?

3227

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?

5

  • 30

    “The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.” –w3schools.com/tags/att_standard_class.asp

    – Triynko

    Apr 7, 2011 at 18:11

  • 17

    element.setAttribute(name, value); Replace name with class. Replace value with whatever name you have given the class, enclosed in quotes. This avoids needing to delete the current class and adding a different one. This jsFiddle example shows full working code.

    May 18, 2014 at 4:59

  • 3

    For changing a class of HTML element with onClick use this code: <input type='button' onclick='addNewClass(this)' value='Create' /> and in javascript section: function addNewClass(elem){ elem.className="newClass"; } Online

    Aug 22, 2017 at 4:13


  • @Triynko – that link on w3schools has changed, looks like in September 2012. Here is that page on Archive.org from 12/Sep/2012: HTML class Attribute-w3schools. Here is the link for the replacement page on w3schools.com: HTML class Attribute-w3schools.

    Oct 12, 2018 at 17:46


  • @ImanBahrampour That will obliterate any existing classes.

    – Teepeemm

    Sep 17, 2021 at 2:53

4404

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') )

document.getElementById("MyElement").classList.toggle('MyClass');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use – you can of course obtain elements in other ways, and in the right situation may simply use this instead – however, going into detail on this is beyond the scope of the answer.

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.)

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 remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character

MyClass  # The literal text for the classname to remove

(?!\S)   # Negative lookahead to verify the above is the whole classname
         # Ensures there is no non-space character following
         # (i.e. must be the end of the string or space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )

### Assigning these actions to onclick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'") this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:

<script type="text/javascript">
    function changeClass(){
        // Code examples from above
    }
</script>
...
<button onclick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
    function changeClass(){
        // Code examples from above
    }

    window.onload = function(){
        document.getElementById("MyElement").addEventListener( 'click', changeClass);
    }
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading – without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)

JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

In addition, jQuery provides a shortcut for adding a class if it doesn’t apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');

### Assigning a function to a click event with jQuery:

$('#MyElement').click(changeClass);

or, without needing an id:

$(':button:contains(My Button)').click(changeClass);

33

  • 120

    Great answer Peter. One question… why is it better to do with with JQuery than Javascript? JQuery is great, but if this is all you need to do – what justifies including the entire JQuery libray instead of a few lines of JavaScript?

    May 15, 2011 at 15:32

  • 25

    @mattstuehler 1) the phrase “better yet x” often means “better yet (you can) x”. 2) To get to the heart of the matter, jQuery is designed to aid in accessing/manipulating the DOM, and very often if you need to do this sort of thing once you have to do it all over the place.

    – Barry

    May 24, 2011 at 16:46

  • 33

    One bug with this solution: When you click on your button multiple times, it will add the Class of ” MyClass” to the element multiple times, rather than checking to see if it already exists. Thus you could end up with an HTML class attribute looking something like this: class="button MyClass MyClass MyClass"

    Sep 13, 2011 at 16:28

  • 37

    If you’re trying to remove a class ‘myClass’ and you have a class ‘prefix-myClass’ the regex you gave above for removing a class will leave you with ‘prefix-‘ in your className :O

    Sep 15, 2011 at 5:26

  • 19

    Wow, three years and 183 upvotes and nobody spotted that until now. Thanks jinglesthula, I’ve corrected the regex so it wont incorrectly remove parts of class names. // I guess this is a good example of why a Framework (like jQuery) is worth using – bugs like this are caught and fixed sooner, and don’t require changes to normal code.

    Sep 15, 2011 at 17:09


467

You could also just do:

document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');

And to toggle a class (remove if exists else add it):

document.getElementById('id').classList.toggle('class');

7

  • 67

    I believe this is HTML5 dependent.

    – John

    Oct 27, 2011 at 17:16

  • 13

    You’ll need Eli Grey’s classList shim.

    Nov 14, 2011 at 14:34

  • 16

    Mozilla Developer Network states that it doesn’t work, natively, in Internet Explorers less than 10. I find the statement to be true, in my testing. Apparently, the Eli Grey shim is required for Internet Explorer 8-9. Unfortunately, I couldn’t find it on his site (even with searching). The shim is available on the Mozilla link.

    – doubleJ

    Oct 29, 2012 at 4:13

  • 2

  • 5

    atow “classList” has partial support in IE10+; no support for Opera Mini; else full support in remaining standard browsers: caniuse.com/#search=classlist

    Jul 29, 2015 at 8:47


139

In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if an element has a class:

function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(ele, cls) {
    if (!hasClass(ele, cls))
        ele.className += " " + cls;
}

function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

So, for example, if I want onclick to add some class to the button I can use this:

<script type="text/javascript">
    function changeClass(btn, cls) {
        if(!hasClass(btn, cls)) {
            addClass(btn, cls);
        }
    }
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>

By now for sure it would just be better to use jQuery.

7

  • 10

    This is great for when your client doesn’t let you use jQuery. (Cause you end up almost building your own library.)

    – Mike

    Jul 24, 2013 at 5:16

  • 2

    @Mike If the client doesn’t let you use jQuery, could you not just go through and rebuild only the features you needed into your own library?

    – kfrncs

    Nov 18, 2013 at 5:04

  • 6

    @kfrncs Because I don’t generally need that large of a framework. For the project I was thinking of, the only functions I needed were the 3 classname(has,add,remove) functions and the cookie(has, add, remove) functions. Everything else was either custom, or natively well supported. So everything together was then only 150 lines before minifying, including comments.

    – Mike

    Nov 18, 2013 at 19:17

  • This is my favorite solution for this. I use it everywhere. I believe it is the most elegant way to achieve adding and removing classes when your project does not already have another way of doing it.

    Oct 17, 2017 at 21:36

  • It should be noted that after using addClass and removeClass on the same element, the element’s className will contain an additional space. The className modifying line of removeClass should be updated to ele.className = ele.className.replace(reg, ' ').trim().replace(/\s{2,}/g, ' ');. This removes trailing whitespace left over and collapses multiple whitespaces into a single space in the className.

    Oct 17, 2017 at 21:45