Add class to <html> with Javascript?
JavascriptHtmlJavascript Problem Overview
How do you add a class to the <html>
root element using Javascript?
Javascript Solutions
Solution 1 - 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');
//
Solution 2 - Javascript
This should also work:
document.documentElement.className = 'myClass';
Edit:
IE 10 reckons it's readonly; yet:
Opera works:
I can also confirm it works in:
-
Chrome 26
-
Firefox 19.02
-
Safari 5.1.7
Solution 3 - Javascript
document.documentElement.classList.add('myCssClass');
classList
is supported since ie10: https://caniuse.com/#search=classlist
Solution 4 - Javascript
Solution 5 - Javascript
You should append class not overwrite it
var headCSS = document.getElementsByTagName("html")[0].getAttribute("class") || "";
document.getElementsByTagName("html")[0].setAttribute("class",headCSS +"foo");
I would still recommend using jQuery to avoid browser incompatibilities
Solution 6 - Javascript
document.getElementsByTagName("html")[0].classList.add('theme-dark');
document.getElementsByTagName("html")[0].classList.remove('theme-dark')
document.getElementsByTagName("html")[0].classList.toggle('theme-dark')
Solution 7 - Javascript
With Jquery... You can add class to html elements like this:
$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');
nameclassorid no point or # at the beginning