If you want to dynamically set or remove a CSS class name for a HTML element, then you need to do some javaScript works. We can do this by using raw javaScript. jQuery is also a popular javaScript library. You can use jQuery also. Here I am showing you the both way to add/remove class.
Using Raw JavaScript:
Removing a class
var id='myElementId'; var myClassName=" className"; //must keep a space before class name var d; d=document.getElementById(id); d.className=d.className.replace(myClassName,"");
Adding a class
var id='myElementId'; var myClassName=" className"; //must keep a space before class name var d; d=document.getElementById(id); d.className=d.className.replace(myClassName,""); // first remove the class name if that already exists d.className = d.className + myClassName; // adding new class name
Using jQuery:
Adding a class
jQuery("#myElementId").addClass('className');
Removing a class
jQuery("#myElementId").removeClass('className');
Remove one class and add another new class at once
jQuery("#myElementId").removeClass('className').addClass('newClass');
Remove one more class at once
jQuery("#myElementId").removeClass('className1 className2');
If you think this codes are helpful to you then don’t forget to share this to others.
These codes may be the answer of following queries
- Javascript function to Add a Class
- Using Javascript to add CSS class
- Javascript function to remove a class
- Remove a CSs class by javaScript
- JS code snippet to add/remove class
- jQuery function to add/remove any CSS class
- jQuery addClass function
- JQuery removeClass function
- Dinamically change style of an HTML element
- Change HTML Class attributes
- javascript add class to element
- javascript remove class
- Add/Remove Class with jquery function
- Adding a class to a .click function
- Add Remove CSS Class Using Fresh JavaScript Without jQuery
Permalink
How about:
document.getElementById(‘id’).classList.add(‘class’);
document.getElementById(‘id’).classList.remove(‘class’);
Permalink
The classList property is not supported by IE9 and lower. IE10+ supports it though.
Use className += ” ..” instead. Note: Do not omit the space: class names should be added in a white-space separated list.
http://stackoverflow.com/questions/8098406/code-with-classlist-does-not-work-in-ie
Thanks for coming up with this new idea
Permalink
You can do that too if you don’t care about < IE9 and other browsers.
Permalink
I would not rely on plain replace() for vanilla JS; instead, I would use RegExp replace() like this:
var re = new RegExp(' *' + myClassName + ' *');
d.className = d.className.replace(re, '');
This way you won’t have to worry about requiring the developer to keep a space before the class name and taking that into account when doing className string comparisons.
Permalink
Very knowledgeable content, helped me build my css and js stock. Although from a marketing team we do sometimes need the css and js knowledge.