[javascript] Add class to <html> with Javascript?

How do you add a class to the <html> root element using Javascript?

This question is related to javascript html

The answer is


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

Compatibility.

Edit:

IE 10 reckons it's readonly; yet:

It worked!?

Opera works:

Works

I can also confirm it works in:

  • Chrome 26
  • Firefox 19.02
  • Safari 5.1.7

I'd recommend that you take a look at jQuery.

jQuery way:

$("html").addClass("myClass");

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