Getting the 〈html〉Tag with Javascript

Although it may rarely happen, but sometimes you may need to access the <html> element with Javascript — probably to add or remove classes dynamically.

You can access the <html> tag through Javascript in 3 ways :

  • Using document.documentElement : document.documentElement returns the root element of a document — in this case it is <html>
    // add class to <html> element
  • Using document.querySelector
    // remove class from <html> element
  • Using document.getElementsByTagName : document.getElementsByTagName returns an array of all elements in the document that has the given tag name. This can be used for the <html> tag also.
    // getElementsByTagName returns an array, so use its first element

Leave a Reply

Your email address will not be published. Required fields are marked *