124

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

5
  • this was one of the questions I asked when I started out. I never did find a good place that mentioned it. I am glad to see it here. Commented Dec 20, 2012 at 21:46
  • Just curious - why would you want to do this? Commented Dec 20, 2012 at 21:49
  • @David To add a fallback in case Modernizr doesn't load. Modernizr adds the class "js" when it loads. Commented Dec 20, 2012 at 21:51
  • 1
    You should really add the class "no-js" to your markup if you are using modernizr. (If modernizr loads it will remove this class) Commented Dec 20, 2012 at 21:54
  • @Kevin - Already did. Go HTML5 Boilerplate! Commented Dec 20, 2012 at 22:02

8 Answers 8

161

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');
//
Sign up to request clarification or add additional context in comments.

5 Comments

FYI, classlist.add/.remove doesn't work on document.documentElement.
@AndyMercer It's classList.add (camel case).
Yes obviously that was a typo. But what I said is still correct. classList doesn't work on document.documetElement.
I tried it in three different browsers before replying, so it wasn't "obviously a typo." (Chrome, Firefox, Safari--root.classList.add('myCssClass') worked in all three.) Are you using IE?
document.documentElement.classList.add seems to work fine here. Have browsers in 2018 started supporting this?
27
document.documentElement.classList.add('myCssClass');

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

Comments

22

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

2 Comments

Your example has INVISIBLE CHARACTERS, namely U+200B after the final apostrophe, causing it to fail compilation in webpack and other compilers!
@entozoon how strange! Thanks for pointing that out. I've fixed it now :)
8

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

jQuery way:

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

6 Comments

You don't need jQuery to select an element with JavaScript.
jQuery is infact easy to learn, and is used most of the time anyway, these days. But yes, you don't need it for this task ;)
yeah, right, we know what jquery is, but answering a purely javascript question with "learn jquery" is what surprised me :)
@aebersold I agree that jQuery is easy to learn and use, but at 50K to download (plus an additional request) just to add a class, it's a bit of overkill IMHO.
@Mick thanks for pointing this out a decade after I wrote this answer.
|
7

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

Comments

2
document.getElementsByTagName("html")[0].classList.add('theme-dark');
document.getElementsByTagName("html")[0].classList.remove('theme-dark')
document.getElementsByTagName("html")[0].classList.toggle('theme-dark')

Comments

-1
<script>
    (function () {
        try {
            const mode = localStorage.getItem('darkMode');
            if (!JSON.parse(mode)) return;
            document.documentElement.classList.add('dark');
        } catch (e) {}
    })();
</script>

1 Comment

This answer just repeats what was already answered a decade(!) ago. All the rest is irrelevant to the question.
-3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.