Add class to <html> with Javascript?

JavascriptHtml

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

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

Solution 3 - Javascript

document.documentElement.classList.add('myCssClass');

classList is supported since ie10: https://caniuse.com/#search=classlist

Solution 4 - Javascript

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

jQuery way:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrandon LebedevView Question on Stackoverflow
Solution 1 - JavascriptKevin BoucherView Answer on Stackoverflow
Solution 2 - Javascriptc24wView Answer on Stackoverflow
Solution 3 - JavascriptTom EsterezView Answer on Stackoverflow
Solution 4 - JavascriptaebersoldView Answer on Stackoverflow
Solution 5 - Javascriptama2View Answer on Stackoverflow
Solution 6 - Javascriptuser7153178View Answer on Stackoverflow
Solution 7 - JavascriptRoos BautistaView Answer on Stackoverflow