Add class to <html>
with JavaScript?
Easily add a new class to your <html>
tag using this quick JavaScript command:
This snippet immediately targets the root <html>
element and appends 'new-class'
to its class list, enabling related CSS styling or JavaScript functionality out of the box.
className vs classList
The old-school way: className
For nostalgics who enjoy the smell of vanilla JS, there’s a direct but slightly clunky way to add classes and keep the existing ones:
Remember to put a space before your class name to avoid mutating the class into something like .existingClassnew-class
.
The facelift: classList
For aesthetes who nod at the mention of modern JavaScript, classList
got you covered. It's a cleaner, safer way to play with classes as it handles spacing and duplication issues for you:
To show off, you can add multiple classes at once:
Cross-browser solutions & legacies
Shout out to the old guys: legacy browsers
With classList
, always cross-check with your favorite browser compatibility guide like caniuse.com. Running an antique as IE9? You might need a workaround or a polyfill.
The Swiss Army Knife: jQuery
Despite being somewhat out of the spotlight, jQuery remains helpful for a cross-browser solution:
Sidebar: interacting with other scripts
Sizing and dancing around in the existing codebase can be tricky. Always be wary of playing too rough with the existing scripts to avoid script conflicts, especially when these scripts rely on className
for styling:
Cross-checks & best practices
A11y should never be an afterthought :wheelchair:
Like any other DOM manipulation, dynamically adding classes can impact accessibility. Ensure your site remains navigation friendly for users with assistive technology.
Keep it clean, keep it green
Inline scripts are fast food. Modular functions in external scripts are home-cooked meals. Choose wisely!
Was this article helpful?