3

I'd like to add a class to the <html> element and run the code for it in the <head> element. What's the best way to do that?

document.getElementsByTagName('html')[0].className = 'class';

or

document.documentElement.className = 'class';

4
  • 1
    Take great care when doing this, especially on the anti-browser. Do test on all supported browsers, because some consider the html element special in some way. Commented Jun 1, 2011 at 0:25
  • Why would you need to add a class to <html> instead of the <body> ? Commented Jun 1, 2011 at 0:26
  • @Teneff, to have less elements on the page. Commented Jun 1, 2011 at 0:27
  • document.body.parentNode Commented Mar 6, 2014 at 4:38

2 Answers 2

4

Neither way is really 'better', but documentElement is a tiny bit faster, because it doesn't have to run the matching function, so go with it.

Sign up to request clarification or add additional context in comments.

1 Comment

document.body.parentNode
3

Modernizr seems to use document.documentElement (by looking at the source).

I guess that's a good reference :)

1 Comment

Typekit uses document.getElementsByTagName, also a good reference ; )

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.