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
Just thought I'd throw this in:
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.
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:
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:
Here's my version, fully working:
Usage:
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