Remove CSS class from element with JavaScript (no jQuery)
Need to evict a class from an element asap? element.classList.remove("ClassName")
in JavaScript gets the job done:
From <div class="troublemaker unwantedClass"></div>
, this quick fix changes it to <div class="troublemaker"></div>
. Handy for real-time style tweaks.
Addressing multiple classes
When an element has multiple classes and you only have beef with one of them, classList
is your new best friend:
Running this on <div id="divaElement" class="costumeChange offKey encore"></div>
, the output is <div id="divaElement" class="encore"></div>
.
Covering old and new tracks
Legacy browsers, bless their hearts, might not play nice with classList
. For IE9 and its brethren, className
is the old reliable friend:
This uses regex to exactly match and replace the class name, ensuring it doesn't trip on classes with similar sounding names.
A touch of fancy coding
For readability and elegance, consider extending HTMLElement's prototype with a custom method:
With this, just call diva.removeClass('mySolo')
, and watch that despised class vanish.
Supporting legacy fans
In a volatile world of user agents, having fallbacks is non-negotiable. Even the universal love for classList
won't excuse skipping graceful degradation:
This function removes classes dependably, regardless of the user's taste in browsers.
Class manipulations, list-style
When classList
ain't enough and regex feels heavy, you can transform the className string into an array, then filter out the nuisance:
This gives you granular control, allowing you to cherry-pick classes to retain.
Building your style entourage
After getting rid of the trash, you might want to roll out the red carpet for some new classes:
Class added, no existing classes disturbed.
Was this article helpful?