How can I change a class of an HTML element in response to an onClick
event using JavaScript?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
You can use
node.className
like so:This should work in IE5.5 and up according to PPK.
Change an element's CSS class with JavaScript in ASP.NET:
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:
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 usethis
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:
(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
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:
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:
(It is not required to have this code in script tags, this is simply for 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
(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 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 ~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 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
$
here is the jQuery object.)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:
This is working for me:
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.
Here's a toggleClass to toggle/add/remove a class on an element:
see jsfiddle
also see my answer here for creating a new class dynamically