How can I change a CSS class of an HTML element in response to an onClick
event using JavaScript?
|
||||
Adding and Removing Classes, with simple cross-browser JavaScriptThe standard JavaScript way to select an element is using To change all classes for an element:To replace all existing classes with one or more new classes, set the className attribute:
(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:
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:
An explanation of this regex is as follows:
The 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:
Assigning these actions to onclick events:Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:
(It is not required to have this code in script tags, this is simply for brevity of example, and including the JS 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
(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 JS is called, so that line would fail.) JavaScript Frameworks and LibrariesThe above code is all in standard JavaScript, however it is common practise 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 ~50KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work, or anything that might have unusual cross-browser behaviour, 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 Changing Classes with jQuery:
In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:
Assigning a function to a click event with jQuery:
or, without needing an id:
HTML5 Techniques for changing classesModern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:
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. |
|||||||||||||||||||||
|
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'); |
|||||||||||||||||||||
|
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:
So, for example, if I want onclick to add some class the the button I can use this:
By now for sure it would just better to use jQuery. |
|||||||||||||
|
You can use
This should work in IE5.5 and up according to PPK. |
||||
|
Using pure JavaScript code:
|
|||||
|
Wow, surprised there are so many overkill answers here...
|
|||||||||||||
|
This is working for me:
|
|||||||||||||
|
Couple of minor notes and tweaks on the regex from above: 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.
|
|||
|
Just to add on information from another popular framework, Google Closures, see their dom/classes class:
One option for selecting the element is using goog.dom.query with a CSS3 selector:
|
|||
|
As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):
And then just use like this (on click will add or remove class):
Here is demo. |
|||||||||
|
Change an element's CSS class with JavaScript in ASP.NET:
|
|||||
|
I would use jQuery and write something like this:
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 |
|||||
|
The line
should be:
|
|||||
|
Here's my version, fully working:
Usage:
|
|||||||||
|
I use the following vanilla JavaScript functions in my code. They use regular expressions and
You can also use element.classList in modern browsers. |
||||
|
Just thought I'd throw this in:
|
|||
|
Here is simple jQuery code to do that.
Here,
Good Luck. |
||||
|
This is easiest with a library like jQuery:
|
|||||||||||||
|
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:
|
|||||||||||||||||||||
|
protected by Community♦ Oct 26 '11 at 15:51
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?
element.setAttribute(name, value);
Replacename
withclass
. Replacevalue
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. – Sandy Good May 18 '14 at 4:59