0

I want to toggle a class to the html tag element. I've made it work with the body element but I cannot find the solution to also toggle a class to the html tag.

document.querySelector('[data-menu-mobile]').addEventListener('click', function(){
    document.body.classList.toggle('nav-main-mobile-open');
    document.html.classList.toggle('html-color-fill');
});

I know this seems to be wrong:

document.html.classList.toggle('html-color-fill');

What is the correct way to do this?

1
  • There is not document.html. Commented Mar 20, 2014 at 15:16

2 Answers 2

2

There's no document.html object, to get to the root element you should use document.documentElement.

document.documentElement.classList.toggle('html-color-fill')

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

4 Comments

This is not html object because the document begins from the html tag downwards? For what reason is this? Just to understand better this answer. Thanks a lot!
You can use the DOM API with more than HTML documents (for example XML or SVG) which may have the root element named differently. document.documentElement is markup language-agnostic way to get the root element, while document.body is a HTML-specific addition to the DOM API.
everything clear except language-agnostic, what do you mean with that?
document.html would be language-specific like document.body and would work only with HTML. document.documentElement is language-agnostic in the sense that it doesn't assume the name of the root element but will get it in whatever markup language that works with DOM API.
0

This should work:

var elements = document.getElementsByClassName("myclass");

//iterate through all found elements
Array.prototype.forEach.call(elements, function(element) {
   element.className = "html-color-fill";
   //or remove class with:
   //element.className = "";
});

3 Comments

classList.add(), .remove() and .toggle() are the solution in modern browsers, the question was how to get the html element.
Thanks for clarification. I did not see any sense for setting class of html element.
@pawel my project requires IE9+ and other modern browsers. So I think this will work perfectly, I'm just practising to not use jquery.

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.