2984

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

Vibhor
  • 113
  • 12
Nathan Smith
  • 32,861
  • 6
  • 25
  • 25
  • 29
    "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." -http://www.w3schools.com/tags/att_standard_class.asp – Triynko Apr 07 '11 at 18:11
  • 15
    `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](http://jsfiddle.net/U2PCA/) shows full working code. – Alan Wells May 18 '14 at 04:59
  • 3
    For changing a class of HTML element with onClick use this code: `` and in javascript section: `function addNewClass(elem){ elem.className="newClass";` } [Online](http://jsbin.com/jucuwo/edit?html,js,output) – Iman Bahrampour Aug 22 '17 at 04: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](http://web.archive.org/web/20120912065825/http://www.w3schools.com/tags/att_standard_class.asp). Here is the link for the replacement page on w3schools.com: [HTML class Attribute-w3schools](https://www.w3schools.com/tags/att_class.asp). – Kevin Fegan Oct 12 '18 at 17:46

34 Answers34

4150

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

Samuel Sorial
  • 123
  • 1
  • 7
Peter Boughton
  • 102,341
  • 30
  • 116
  • 172
  • 115
    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? – mattstuehler May 15 '11 at 15:32
  • 23
    @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 '11 at 16:46
  • 4
    Be ware of that in case of Add Class Name there MUSt be White Space in front of the Class Name you want to add. – didxga Jul 13 '11 at 07:07
  • 1
    if you add a class does the previous class get removed, or you have to do that manually? – Gabor Magyar Jul 27 '11 at 19:22
  • 1
    Previous classes will stay. You'll have to remove other classes manually if you want to do that. – Micharch54 Aug 03 '11 at 19:15
  • 32
    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"` – Web_Designer Sep 13 '11 at 16:28
  • 9
    I guess the solution to that would be: `if ( ! document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )` or, with jQuery: `if ( ! $j('#MyElement').hasClass('MyClass') )` (although I suspect addClass wont add duplicates?) – Peter Boughton Sep 14 '11 at 00:14
  • 35
    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 – jinglesthula Sep 15 '11 at 05:26
  • 17
    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. – Peter Boughton Sep 15 '11 at 17:09
  • 2
    I've done some minor edits to improve the answer - hopefully people agree they are improvements? If there's anything else I've missed let me know (or just edit the answer yourself). – Peter Boughton Sep 15 '11 at 17:24
  • 2
    @PeterBoughton Not sure if you think this is an improvement, but I like: `(' '+document.getElementById("MyElement").className+' ').replace( ' '+MyClass+' ' , '' )` – Paul Dec 21 '11 at 09:38
  • 1
    @PaulP.R.O. you are collapsing the surrounding spaces and regex to a null, which will concatenate the surrounding class name strings (if any) together. I think elem.className = elem.className.replace( ' ' + classname + ' ' , ' ' ) is what we want. Thanks! – Cris Stringfellow Jun 04 '12 at 10:40
  • 2
    I use similar methods, but with a g (general) regex. the reason is exactly the issue described by @Web_Designer above: if the user clicks several times, you end up with multiple instances of the same class, and all instances must be removed to remove the class. – Christophe Aug 15 '12 at 00:06
  • 1
    Importing an entire library to accomplish one, simple task is precisely why there is so much overhead drifting around the internet. So I disagree that resorting to JQuery is the "better" solution. – b1nary.atr0phy Oct 03 '12 at 01:01
  • 3
    I have just made substantial additions to this answer - the bulk is the same, but I would appreciate feedback on if there's any mistakes or places for further improvement. – Peter Boughton Dec 12 '12 at 18:24
  • 4
    When creating the regex with a variable for the class name I had to look up the syntax: `var regExp = new RegExp('(?:^|\\s)' + classToAddOrRemove + '(?!\\S)', 'g');` – Walter Jan 30 '13 at 16:44
  • 2
    One important detail missing here is the difference between framework and library. jQuery is a library, not a framework. Just for the safe of the example, a framework would be angularJs, for example. – brunoais Apr 08 '13 at 07:23
  • 2
    _(You can specify a space-delimited list of elements.)_ You must mean a list of classes to assign, not elements to select. – DrJonOsterman Aug 02 '13 at 21:23
  • Really excellent answer that fails completely to answer the OP's question: how do you *change* the value of an existing class? – Peter Flynn Jan 06 '14 at 10:13
  • 1
    If it doesn't answer the OP's question, why did they mark it as the solution? _Your question_ appears to be a different one (possibly you want to change the CSS properties/declarations linked to a class name? not sure if browsers allow that) - why not clarify what you're after in a [new question](http://stackoverflow.com/questions/ask) which explains precisely what you want / are trying to achieve? – Peter Boughton Jan 06 '14 at 16:37
  • With regards to the "To add an additional class to an element" point (2nd in list), I find it's best to grab the current `el.className`, string concat with `" class-to-add"`, and finally call a `.trim()` on the string before updating the target element. That said, I don't think CSS really cares about the `\s`, an element's individual classes are determined by a space-separated list anyway. –  Jan 22 '15 at 09:26
  • heh: `var a=[];e.className=((a=e.className.split(" ")).splice(a.indexOf(oldClass),1,newClass)&&a).join(" ").trim();` :D – Duncan Mar 06 '15 at 19:04
  • Can you please rearrange things? **In my opinion** the classList with shim for browser support should be at the top. – Marcel Burkhard Jun 02 '15 at 13:04
  • 1
    would b cool if smth like this worked too, to remove a class name: `document.getElementById("MyElement").className -= " MyClass";` – Nick Humphrey Jul 29 '15 at 08:53
  • 1
    so the answer simply is $('#MyElement').toggleClass('MyClass'); thanks, It works for me – Shady Mohamed Sherif Oct 05 '15 at 14:15
  • Hello there. I was wondering what you would say about using word boundaries instead of (?:\s) at the beginning and (?!\S) near the end of your regular expression. Comments? `document.getElementById("MyElement").className.replace( /\bMyClass\b/g , '' )`. I never seem to have reason to use many of the regular expression short cuts, but this seems (seems) like it could work too. Although, \b has limits on what it considers to be a word character, and you never know what someone might use as a class name. – Anthony Rutledge Nov 07 '15 at 09:57
  • 2
    \b matches next to hyphens. – Peter Boughton Nov 07 '15 at 14:23
  • There are faster methods than removing class using RegExp, especially if you're going to turn it into a polyfill. See http://jsperf.com/removeclass-methods – thdoan Nov 24 '15 at 08:48
  • The code in the **To remove a class from an element:** and **To check if a class is already applied to an element:** sections are missing `;` from the end of the line. Is there a reason for this? It would also be nice if there was a note in **To remove a class from an element:** indicating what happens to spaces. Otherwise, this is a very good answer. – Trisped Mar 21 '16 at 18:38
  • I would prefer `(^start(\s+start)*\s*)|((?:\s+)start(?!\S+))` to remove the word `start` from a whitespace-separeted list. – Andreas Dyballa May 24 '16 at 12:18
  • Angular: angular.element(document.getElementById("MyElement")).removeClass("class-name"); angular.element(document.getElementById("MyElement")).addClass("class-name") – Zymotik Jun 02 '16 at 13:59
  • Hi this is very nice answer. I want change class on some condition on loading html not click event on button. please refer to this question: http://stackoverflow.com/questions/38028756/change-button-class-in-angular-on-some-condition-when-html-loading – pankaj Jun 25 '16 at 14:13
  • Your method for removing a class *almost* takes care of removing extra spaces that may appear after removing items. But it can happen that the result will start with a leading space. If you add a .trim(), your method for removing a class will not contain any extra spaces. – rosell.dk Oct 17 '16 at 20:42
  • Also, you can safely remove the "?:" in the beginning of the RegEx, such that it reads: new RegExp​("​(\\s|^​)"+className+"​(?!\\S​)","g"​) – rosell.dk Oct 17 '16 at 20:45
  • I have created an extensive test of alternatives for removing a class name. Your solution is in the test. The test is [available here](http://picoquery.com/lab/youmightnotneedjquery-tests/removeclass/) – rosell.dk Oct 17 '16 at 20:48
  • @Zymotik you may want to add another separate answer instead of editing someone else's answer. It's a helpful snippet but it should be it's own answer. – TankorSmash Mar 01 '17 at 17:32
  • @PoornaSenaniGamage - Your edit says the reason was "improved formatting", I wonder how you could consider it an "improvement"? It was fine before your edit, and well, it's just "fine" after your edit. You just replaced one standard code formatting method that is preferred (well, at least chosen) by the original author, with another standard code formatting method that you happen to prefer. That your edit was approved is a mystery to me, as it seems to me to be an inappropriate edit. Agreed that this is not an extremely significant issue. Someone else, please let me know if I'm out of line. – Kevin Fegan Oct 12 '18 at 19:27
  • Excellent answer, too bad you left out an example for "(You can use a space-delimited list to apply multiple classes.)" because that would have saved so much time. – JGallardo Oct 17 '19 at 12:25
442

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');
johannchopin
  • 7,327
  • 6
  • 22
  • 62
Tyilo
  • 25,959
  • 32
  • 101
  • 183
  • 66
    I believe this is HTML5 dependent. – John Oct 27 '11 at 17:16
  • 12
    You’ll need Eli Grey’s `classList` shim. – ELLIOTTCABLE Nov 14 '11 at 14:34
  • 15
    [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/DOM/element.classList) 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](http://eligrey.com) 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 '12 at 04:13
  • Feature not supported until a few hours ago (added on IE10 and Android 3) – andreszs Aug 02 '14 at 23:13
  • 1
    [Here's the MDN Documentation for `classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). – Ajedi32 Jun 15 '15 at 15:56
  • 4
    atow "classList" has partial support in IE10+; no support for Opera Mini; else full support in remaining standard browsers: http://caniuse.com/#search=classlist – Nick Humphrey Jul 29 '15 at 08:47
  • I think the Eli Grey shim can be found [here](https://github.com/eligrey/classList.js/)... – Wilf Sep 06 '15 at 16:54
128

In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if element has 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.

Wyck
  • 5,985
  • 4
  • 34
  • 44
Andrew Orsich
  • 49,434
  • 15
  • 132
  • 132
  • 9
    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 '13 at 05:16
  • 1
    @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 '13 at 05:04
  • 5
    @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 '13 at 19:17
  • 2
    Dude, its 4am and thank you much. Vanilla JS is what we're use on my project and this was a life saver. – LessQuesar Dec 16 '15 at 09:25
  • 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. – WebWanderer Oct 17 '17 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. – WebWanderer Oct 17 '17 at 21:45
83

You can use node.className like so:

document.getElementById('foo').className = 'bar';

This should work in IE5.5 and up according to PPK.

Eric Wendelin
  • 39,122
  • 8
  • 59
  • 87
55

Wow, surprised there are so many overkill answers here...

<div class="firstClass" onclick="this.className='secondClass'">
Travis J
  • 77,009
  • 39
  • 185
  • 250
52

Using pure JavaScript code:

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

function addClass(ele, cls) {
    if (!this.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, ' ');
    }
}

function replaceClass(ele, oldClass, newClass){
    if(hasClass(ele, oldClass)){
        removeClass(ele, oldClass);
        addClass(ele, newClass);
    }
    return;
}

function toggleClass(ele, cls1, cls2){
    if(hasClass(ele, cls1)){
        replaceClass(ele, cls1, cls2);
    }else if(hasClass(ele, cls2)){
        replaceClass(ele, cls2, cls1);
    }else{
        addClass(ele, cls1);
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
PseudoNinja
  • 2,677
  • 1
  • 25
  • 35
36

This is working for me:

function setCSS(eleID) {
    var currTabElem = document.getElementById(eleID);

    currTabElem.setAttribute("class", "some_class_name");
    currTabElem.setAttribute("className", "some_class_name");
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gopal Krishna Ranjan
  • 798
  • 1
  • 11
  • 21
24

As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):

HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;

HTMLElement.prototype.addClass = function(string) {
  if (!(string instanceof Array)) {
    string = string.split(' ');
  }
  for(var i = 0, len = string.length; i < len; ++i) {
    if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
      this.className = this.className.trim() + ' ' + string[i];
    }
  }
}

HTMLElement.prototype.removeClass = function(string) {
  if (!(string instanceof Array)) {
    string = string.split(' ');
  }
  for(var i = 0, len = string.length; i < len; ++i) {
    this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
  }
}

HTMLElement.prototype.toggleClass = function(string) {
  if (string) {
    if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
      this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
    } else {
      this.className = this.className.trim() + ' ' + string;
    }
  }
}

HTMLElement.prototype.hasClass = function(string) {
  return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}

And then just use like this (on click will add or remove class):

document.getElementById('yourElementId').onclick = function() {
  this.toggleClass('active');
}

Here is demo.

moka
  • 21,690
  • 4
  • 48
  • 65
  • 1
    this one is a little verbose...here is a very succinct solution...http://jsfiddle.net/jdniki/UaT3P/ – zero_cool Aug 18 '14 at 19:28
  • 5
    Sorry @Jackson_Sandland but you've totally missed the point, which is not to use jQuery at all. – moka Aug 21 '14 at 08:36
20

Just to add on information from another popular framework, Google Closures, see their dom/classes class:

goog.dom.classes.add(element, var_args)

goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)

goog.dom.classes.remove(element, var_args)

One option for selecting the element is using goog.dom.query with a CSS3 selector:

var myElement = goog.dom.query("#MyElement")[0];
Ben Flynn
  • 17,294
  • 18
  • 92
  • 133
17

A couple of minor notes and tweaks on the previous regexes:

You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.

This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.

var s = "testing   one   four  one  two";
var cls = "one";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Alex Robinson
  • 549
  • 4
  • 4
16

Change an element's CSS class with JavaScript in ASP.NET:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
        lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
        lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
        lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
    End If
End Sub
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Hiren Kansara
  • 181
  • 1
  • 4
14

I would use jQuery and write something like this:

jQuery(function($) {
    $("#some-element").click(function() {
        $(this).toggleClass("clicked");
    });
});

This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.

Yes you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.

Thanks

shingokko
  • 364
  • 2
  • 7
  • 8
    You only have to write `jQuery` in its long form once. `jQuery(function($) { });` makes `$` available inside the function in all cases. – ThiefMaster Jun 13 '12 at 14:38
13

The line

document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')

should be:

document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Eric Bailey
  • 171
  • 1
  • 2
  • 8
    Incorrect. The RegEx is delimeted by the forward slashes. Adding quotes causes it to fail in IE, returning the string of the class you're trying to remove rather than actually removing the class. – Dylan Aug 14 '11 at 21:46
12

Change an element's class in vanilla JavaScript with IE6 support

You may try to use node attributes property to keep compatibility with old browsers even IE6:

function getClassNode(element) {
  for (var i = element.attributes.length; i--;)
    if (element.attributes[i].nodeName === 'class')
      return element.attributes[i];
}

function removeClass(classNode, className) {
  var index, classList = classNode.value.split(' ');
  if ((index = classList.indexOf(className)) > -1) {
    classList.splice(index, 1);
    classNode.value = classList.join(' ');
  }
}

function hasClass(classNode, className) {
  return classNode.value.indexOf(className) > -1;
}

function addClass(classNode, className) {
  if (!hasClass(classNode, className))
    classNode.value += ' ' + className;
}

document.getElementById('message').addEventListener('click', function() {
  var classNode = getClassNode(this);
  var className = hasClass(classNode, 'red') && 'blue' || 'red';

  removeClass(classNode, 'red');
  removeClass(classNode, 'blue');

  addClass(classNode, className);
})
.red {
  color: red;
}
.red:before {
  content: 'I am red! ';
}
.red:after {
  content: ' again';
}
.blue {
  color: blue;
}
.blue:before {
  content: 'I am blue! '
}
<span id="message" class="">Click me</span>
Eugene Tiurin
  • 3,383
  • 3
  • 30
  • 32
10

Here's my version, fully working:

function addHTMLClass(item, classname) {
    var obj = item
    if (typeof item=="string") {
        obj = document.getElementById(item)
    }
    obj.className += " " + classname
}

function removeHTMLClass(item, classname) {
    var obj = item
    if (typeof item=="string") {
        obj = document.getElementById(item)
    }
    var classes = ""+obj.className
    while (classes.indexOf(classname)>-1) {
        classes = classes.replace (classname, "")
    }
    obj.className = classes
}

Usage:

<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
alfred
  • 932
  • 9
  • 13
  • 4
    That will break class `foobar` if you try to remove class `foo`. The JS in the intrinsic event handler attributes was broken before being edited. The 4 year old accepted answer is much better. – Quentin Oct 17 '12 at 12:25
  • 1
    thanks, i fixed it (not the prefix problem). it's the old accepted answer that have a bug with the regexp. – alfred Oct 17 '12 at 12:27
  • The code still have the `foobar` problem. See the test [here](http://picoquery.com/lab/youmightnotneedjquery-tests/removeclass/) – rosell.dk Oct 17 '16 at 12:11
10

Here's a toggleClass to toggle/add/remove a class on an element:

// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
    var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
    var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));

    elem.className=elem.className.replace(matchRegExp, ''); // clear all
    if (add) elem.className += ' ' + theClass;
}

see jsfiddle

also see my answer here for creating a new class dynamically

Community
  • 1
  • 1
kofifus
  • 11,635
  • 8
  • 73
  • 114
8

I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf but do not require quoting special characters in regular expressions.

function addClass(el, cn) {
    var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
        c1 = (" " + cn + " ").replace(/\s+/g, " ");
    if (c0.indexOf(c1) < 0) {
        el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
    }
}

function delClass(el, cn) {
    var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
        c1 = (" " + cn + " ").replace(/\s+/g, " ");
    if (c0.indexOf(c1) >= 0) {
        el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
    }
}

You can also use element.classList in modern browsers.

Salman A
  • 229,425
  • 77
  • 398
  • 489
5

THE OPTIONS.

Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList to do what you want.

style vs. classList

The difference between style and classList is that with style you're adding to the style properties of the element, but classList is kinda controlling the class(es) of the element (add, remove, toggle, contain), I will show you how to use the add and remove method since those are the popular ones.


Style Example

If you want to add margin-top property into an element, you would do in such:

// Get the Element
const el = document.querySelector('#element');

// Add CSS property 
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.

classList Example

Let say we have a <div class="class-a class-b">, in this case, we have 2 classes added to our div element already, class-a and class-b, and we want to control what classes remove and what class to add. This is where classList becomes handy.

Remove class-b

// Get the Element
const el = document.querySelector('#element');

// Remove class-b style from the element
el.classList.remove("class-b")

Add class-c

// Get the Element
const el = document.querySelector('#element');

// Add class-b style from the element
el.classList.add("class-c")


Community
  • 1
  • 1
Brian Nezhad
  • 5,772
  • 8
  • 39
  • 67
5

The OP question was How can I change an element's class with JavaScript?

Modern browsers allow you to do this with one line of javascript:

document.getElementById('id').classList.replace('span1','span2')

The classList attribute provides a DOMTokenList which has a variety of methods. You can operate on an element's classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), entries()

Peter Boughton's answer is a great one but it's now over a decade old. All modern browsers now support DOMTokenList - see https://caniuse.com/#search=classList and even IE11 supports some DOMTokenList methods

timbo
  • 9,491
  • 5
  • 45
  • 59
3

OK, I think in this case you should use jQuery or write your own Methods in pure javascript, my preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.

I'd like to do something like below as methods to my javascript framework to add few functionalities which handle adding classes, deleting classes, etc similar to jQuery, this is fully supported in IE9+, also my code is written in ES6, so you need to make sure your browser support it or you using something like babel, otherwise need to use ES5 syntax in your code, also in this way, we finding element via ID, which means the element needs to have an ID to be selected:

//simple javascript utils for class management in ES6
var classUtil = {

  addClass: (id, cl) => {
    document.getElementById(id).classList.add(cl);
  },

  removeClass: (id, cl) => {
    document.getElementById(id).classList.remove(cl);
  },

  hasClass: (id, cl) => {
    return document.getElementById(id).classList.contains(cl);
  },

  toggleClass: (id, cl) => {
    document.getElementById(id).classList.toggle(cl);
  }

}

and you can simply call use them as below, imagine your element has id of 'id' and class of 'class', make sure you pass them as a string, you can use the util as below:

classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');
Alireza
  • 83,698
  • 19
  • 241
  • 152
3

try

element.className='second'

function change(box) { box.className='second' }
.first  { width:  70px; height:  70px; background: #ff0                 }
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
<div onclick="change(this)" class="first">Click me</div>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
2

Just thought I'd throw this in:

function inArray(val, ary){
  for(var i=0,l=ary.length; i<l; i++){
    if(ary[i] === val){
      return true;
    }
  }
  return false;
}
function removeClassName(classNameS, fromElement){
  var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
  for(var i=0,l=s.length; i<l; i++){
    if(!iA(s[i], x))r.push(s[i]);
  }
  fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
  var s = toElement.className.split(/\s/);
  s.push(c); toElement.className = s.join(' ');
}
StackSlave
  • 10,198
  • 2
  • 15
  • 30
2

just say myElement.classList="new-class" unless you need to maintain other existing classes in which case you can use the classList.add, .remove methods.

var doc = document;
var divOne = doc.getElementById("one");
var goButton = doc.getElementById("go");

goButton.addEventListener("click", function() {
  divOne.classList="blue";
});
div{
  min-height:48px;
  min-width:48px;
}
.bordered{
  border: 1px solid black;
}
.green{
  background:green;
}
.blue{
  background: blue;
}
<button id="go">Change Class</button>

<div id="one" class="bordered green">

</div>
Ronnie Royston
  • 11,959
  • 5
  • 57
  • 72
2

classList DOM API:

A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:

const el = document.getElementById("main");
console.log(el.classList);
<div class="content wrapper animated" id="main"></div>

We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

Example:

const el = document.getElementById('container');


function addClass () {
   el.classList.add('newclass');
}


function replaceClass () {
     el.classList.replace('foo', 'newFoo');
}


function removeClass () {
       el.classList.remove('bar');
}
button{
  margin: 20px;
}

.foo{
  color: red;
}

.newFoo {
  color: blue;
}

.bar{
  background-color:powderblue;
}

.newclass{
  border: 2px solid green;
}
<div class="foo bar" id="container">
  "Sed ut perspiciatis unde omnis 
  iste natus error sit voluptatem accusantium doloremque laudantium, 
  totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et 
  quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam 
  voluptatem quia voluptas 
 </div>
  
<button onclick="addClass()">AddClass</button>
  
<button onclick="replaceClass()">ReplaceClass</button>
  
<button onclick="removeClass()">removeClass</button>
  
Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113
2

Yes there is many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.

const tabs=document.querySelectorAll('.menu li');

for(let tab of tabs){
  
  tab.onclick=function(){
    
  let activetab=document.querySelectorAll('li.active');
    
  activetab[0].classList.remove('active')
  
    tab.classList.add('active'); 
  }
  
}
body {
    padding:20px;
    font-family:sans-serif;    
}

ul {
    margin:20px 0;
    list-style:none;
}

li {
    background:#dfdfdf;
    padding:10px;
    margin:6px 0;
    cursor:pointer;
}

li.active {
    background:#2794c7;
    font-weight:bold;
    color:#ffffff;
}
<i>Please click an item:</i>

<ul class="menu">
  <li class="active"><span>Three</span></li>
  <li><span>Two</span></li>
  <li><span>One</span></li>
</ul>
Danish Khan
  • 189
  • 7
2

Lots of answers, lots of good answers.

TL;DR :

document.getElementById('id').className = 'class'

OR

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

That's it.

And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer, it's perfect.

Note:
This is possible with (document or event):

  • getElementById()
  • getElementsByClassName()
  • querySelector()
  • querySelectorAll()
J. Scott Elblein
  • 3,179
  • 11
  • 44
  • 72
tfont
  • 9,576
  • 4
  • 48
  • 51
2
function classed(el, class_name, add_class) {
  const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
  if (add_class && !el.className.match(re)) el.className += " " + class_name
  else if (!add_class) el.className = el.className.replace(re, '');
}

using the accepted answer above here is a simple cross-browser function to add and remove class

add class:

classed(document.getElementById("denis"), "active", true)

remove class:

classed(document.getElementById("denis"), "active", false)
donatso
  • 98
  • 3
2

There is a property className in javascript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.

<!DOCTYPE html>
<html>
<head>
<title>How to change class of an HTML element in Javascript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />

<center><button id="change-class">Change Class</button></center>

<script>
var change_class=document.getElementById("change-class");
change_class.onclick=function()
{
    var icon=document.getElementById("icon");
    icon.className="fa fa-gear";
}

</script>
</body>
</html>

Credit - https://jaischool.com/javascript-lang/how-to-change-class-name-of-an-html-element-in-javascript.html

1

To simply put there are 3 different actions that can be performed on the element:

  1. Add a new class
  2. Remove old class
  3. Toggle class (if the class is then remove it; if the class isn't then add)

But here you are only interested in adding a new class and removing the old ones.

There are 2 ways to do this:

  1. Using add and remove method of classList property of the element. element.classList.add(class_name) with element.classList.remove(old_class_name). It will add new class and remove old one.

Full code

function changeClass() { 
    const element = document.getElementById("id1");
    element.classList.add("new-class");
    element.classList.remove("old-class");
}
.old-class { background: lightpink }
.new-class { background: lightgreen }
<div class="old-class" id="id1">My div element.</div>
<button onclick="changeClass()">Change class</button>
  1. Using className property of the element. element.className = new_class. This will replace all old classes of the element.
    function changeClass() { 
        const element = document.getElementById("id1");
        element.className = "new-class";
    }
    .old-class { background: lightpink }
    .new-class { background: lightgreen }
    <div class="old-class" id="id1">My div element.</div>
    <button onclick="changeClass()">Change class</button>
1

You can add new classes using .classList.add('calss')

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

As well as you can remove classes using .classList.remove('calss')

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

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

document.getElementById('id').classList.toggle('class');
Tharindu Lakshan
  • 538
  • 1
  • 6
  • 22
-1

Working JavaScript code:

<div id="div_add" class="div_add">Add class from Javascript</div>
<div id="div_replace" class="div_replace">Replace class from Javascript</div>
<div id="div_remove" class="div_remove">Remove class from Javascript</div>
<button onClick="div_add_class();">Add class from Javascript</button>
<button onClick="div_replace_class();">Replace class from Javascript</button>
<button onClick="div_remove_class();">Remove class from Javascript</button>
<script type="text/javascript">
    function div_add_class()
    {
        document.getElementById("div_add").className += " div_added";
    }
    function div_replace_class()
    {
        document.getElementById("div_replace").className = "div_replaced";
    }
    function div_remove_class()
    {
        document.getElementById("div_remove").className = "";
    }
</script>

You can download a working code from this link.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sajid
  • 59
  • 1
  • 11
-3

Here is simple jQuery code to do that.

$(".class1").click(function(argument) {
    $(".parentclass").removeClass("classtoremove");
    setTimeout(function (argument) {
        $(".parentclass").addClass("classtoadd");
    }, 100);
});

Here,

  • Class1 is a listener for an event.
  • The parent class is the class which hosts the class you want to change
  • Classtoremove is the old class you have.
  • Class to add is the new class that you want to add.
  • 100 is the timeout delay during which the class is changed.

Good Luck.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
uttamcafedeweb
  • 81
  • 1
  • 10
-25

This is easiest with a library like jQuery:

<input type="button" onClick="javascript:test_byid();" value="id='second'" />

<script>
function test_byid()
{
    $("#second").toggleClass("highlight");
}
</script>
Jon Galloway
  • 50,160
  • 24
  • 120
  • 192
  • 7
    What does the javascript: pseudo-protocol do in a script-event ... It seems totally stupid to tell the javascript-interpretator, that it should treat script in a script-event as script !-) Only use of the javascript: pseudo-protocol is where you instead would use an url !o] – roenving Oct 12 '08 at 20:20
  • 5
    In that context, it isn't the pseudo-protocol - it's a loop label ... only there is no loop for it TO label. – Quentin Oct 13 '08 at 08:19
  • 8
    Actually, that is not a pseudo-protocol, it is interpreted as a JavaScript label, like what you can use in a loop. One could easily do `onClick="myScriptYo:do_it();"`. But, please, don't do it. – kzh Mar 09 '11 at 20:32
-65

No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.

The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:

Never ever change className on-the-fly !-)

But usually you'll only need to change a property or two, and that is easily implemented:

function highlight(elm){
    elm.style.backgroundColor ="#345";
    elm.style.color = "#fff";
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
roenving
  • 2,372
  • 12
  • 14
  • 16
    i've never experienced any performance issues with switching CSS classes myself. I think whatever performance hit there *might* be, it's far outweighed by the messiness of having styles/presentation mixed up in your javascript. – nickf Oct 12 '08 at 20:46
  • 5
    Hrm, obviously you never tested it ... In a realtime application consisting of thousands of rows nested with other elements I recognized a delay of several seconds, remaking it only to change properties it wasn't possible to recognize delay ... – roenving Oct 12 '08 at 20:51
  • 6
    Why would you even want thousands of rows nested with other elements? Also, what operating system & browser was this delay with? – Peter Boughton Oct 12 '08 at 21:49
  • 41
    If changing a className is causing noticeable performance problems, you have much bigger problems in the structure and design of your page/app. If not, shaving off a few milliseconds is not a good reason to pollute your application logic with styles. – eyelidlessness Oct 13 '08 at 03:33
  • 31
    this is the worst idea ever. changing classes is by far and away the easiest and cleanest way to update your CSS on the fly. – Jason Dec 08 '09 at 22:19
  • 5
    To the “thousands of rows” unbelievers: doxygen. Hierarchical, collapsible menus in a side frame. IE7 had fatal issues with this so I used Firefox. – Erik Olson Jun 24 '11 at 15:39
  • 2
    I'm wondering why you haven't deleted your answer yet! *(it's 2016)* – Alex Jolig Jan 31 '16 at 19:00
  • 2
    @AlexJolig - the user hasn't logged in since 2009 – Krease Jun 10 '16 at 16:47
  • 3
    This is the second-most downvoted answer on the site. – Mr Anderson Sep 01 '16 at 20:01
  • 1
    I think "don't do it in the first place" is not an acceptable answer for "how to do it". – Lajos Mészáros Apr 18 '17 at 11:25
  • 2
    So instead of changing a class you go with writing inline styles by hand. You are taking CSS's job. By the way, if you edit the style attribute, it will also redraw the page as it would if you would have changed the class. _"obviously you never tested it"_ - show us some exact data on how your solution is faster. And please don't give us data like "It's 40% faster, when you execute 20 million changes" or something like that. – Lajos Mészáros Apr 18 '17 at 11:32