Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
17

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');
//

[#81295] Wednesday, December 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;