75
rated 0 times
[
78]
[
3]
/ answers: 1 / hits: 144244
/ 12 Years ago, thu, december 20, 2012, 12:00:00
How do you add a class to the <html>
root element using Javascript?
More From » html
How do you add a class to the <html>
root element using Javascript?
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');
//