DrMeers
DrMeers

Reputation: 4207

How to most reliably/simply access the <html> element via javascript?

Use case: I'd like to dynamically add classes to the <html> element in my document so that some SASS mixins that are currently using .class-name & will work if applied within a selector which includes a body class -- otherwise I get .class-name .body-class .rest-of-selector which doesn't work unless class-name is applied at a higher level than the <body>

Previously I've used document.body.classList.add which seems neat, simple and robust.

In transitioning to add classes to the <html> element instead, I wondered what the equivalent code would be:

Upvotes: 2

Views: 888

Answers (1)

alexalexalex09
alexalexalex09

Reputation: 61

As @thibsc and @LouysPatriceBessette said above, you have two excellent options in document.querySelector("html") and document.documentElement.

document.querySelector("html")

document.querySelector() is an important function to know in general, in addition to document.querySelectorAll(). It returns the first matching element in document order, which for `document.querySelectorAll("html") will be the root html object.

CanIUse compatibility chart

document.documentElement

The documentElement property of the document object (which can be thought of as an alias to the HTMLDocument object) always refers to the root element, which in HTML is generally the <html> tag.

CanIUse compatibility chart

Speed

In my super-scientific speed test, document.documentElement seems faster today:

let date = Date.now();
for (var i=0; i<123456; i++) {
    a = document.querySelector("html");
    a.classList.toggle("hello");
    a = null;
}
console.log(Date.now() - date);
//result: 254

let a;
let date = Date.now();
for (var i=0; i<123456; i++) {
    a = document.documentElement;
    a.classList.toggle("hello");
    a = null;
}
console.log(Date.now() - date);
//result: 225

In the end, your question is about what "feels" good - but these are the best ways to access the <html> element. You were correct about your other alternatives:

  • document.html -- doesn't exist
  • document.rootElement -- deprecated
  • document.getElementsByTagName('html')[0] -- Clunky but robust
  • document.body.parentElement -- Also robust

But perhaps what you want is this:

const $ = document.querySelector.bind(document);
$("html").classList.add("myClass");

Upvotes: 4

Related Questions