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
    document.documentElement.classList.add('smooth-scroll');
    
  • Using document.querySelector

    // remove class from <html> element
    document.querySelector("html").classList.remove('smooth-scroll');
    
  • 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
    document.getElementsByTagName("html")[0].classList.remove('smooth-scroll');