How to add and remove classes in Javascript without jQuery
Quickly toggle classes using classList
API:
Add:
Remove:
This API offers an efficacious way to manipulate DOM element classes, rendering jQuery superfluous.
Browser adaptation: A Tale of Old and New
While classList
is a key component in modern browsers, it's a tragic tale for older browsers such as IE8 — classList
isn't present. Here's the JavaScript wizardry needed.
Adding a class:
Removing a class:
Remember, not all hope is lost for older browsers — Polyfills for classList
can be your knights in shining armor!
It's a toggle world
Level up your class toggling with classList.toggle
, adding a little spice of conditional logic:
Toggle:
The condition
is your boolean gatekeeper — if true
, the class enters; if false
, it's time to pack up.
Security checks in place
Handling class names comes with its own set of rules. For the love of security, treat user input-derived class names with the utmost respect to prevent CSS injection attacks.
Think about performance
Mindful manipulation can prevent a performance conundrum. classList
methods come optimized, but the heavy demands of complex rendering or a tight loop may push the browser to its limit.
Exploring the road less taken
Like a shapeshifter, classList
takes on multiple faces - even when it goes by the name className
!
Check out these alternative transformation techniques:
Set classes:
Check class existence:
The className
methods might not be the prettiest, but provide the baseline functionality sans additional dependencies.
Tips and Traps
A few wise words and coding pitfalls to watch out for:
Multiple classes: classList
is no one-trick pony. It handles multiple classes effortlessly:
Trap 1 - Whitespace surprise: Eliminate unexpected whitespaces in class names unless you favor surprising CSS or JavaScript behaviours.
Trap 2 - Unique classes: JavaScript won't protest against duplicate class names. Keep them unique to sidestep style clashes.
Was this article helpful?