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
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:
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:
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:just say
myElement.classList="new-class"
unless you need to maintain other existing classes in which case you can use theclassList.add, .remove
methods.Working JavaScript code:
You can download a working code from this link.
Here is simple jQuery code to do that.
Here,
Good Luck.
This is easiest with a library like jQuery: