How do you add a class to the <html>
root element using Javascript?
This question is related to
javascript
html
document.getElementsByTagName("html")[0].classList.add('theme-dark');
document.getElementsByTagName("html")[0].classList.remove('theme-dark')
document.getElementsByTagName("html")[0].classList.toggle('theme-dark')
document.documentElement.classList.add('myCssClass');
classList
is supported since ie10: https://caniuse.com/#search=classlist
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:
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
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
Source: Stackoverflow.com