How do you add a class to the <html>
root element using Javascript?
HTML. Using . add() method: This method is used to add a class name to the selected element.
JavaScript provides 2 different ways by which you can add classes to HTML elements: Using element. classList. add() Method.
Like this:
var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag) root.setAttribute( 'class', 'myCssClass' );
Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)
root.className += ' myCssClass';
Or, depending on the required browser support, you can use the classList.add()
method:
root.classList.add('myCssClass');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist
UPDATE:
A more elegant solution for referencing the HTML
element might be this:
var root = document.documentElement; root.className += ' myCssClass'; // ... or: // root.classList.add('myCssClass'); //
This should also work:
document.documentElement.className = 'myClass';
Compatibility.
Edit:
IE 10 reckons it's readonly; yet:
Opera works:
I can also confirm it works in:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With