Reputation: 4207
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:
document.html
-- nope, no such thing it seemsdocument.rootElement
-- should work I think, but was null
when I tested so not robust?!document.getElementsByTagName('html')[0]
-- pretty clunky, but surely effective/robust?document.body.parentElement
-- looks cleaner, should be reliable? Is this as direct as it gets?document.querySelector('html')
as suggested by Louys below -- feels like we shouldn't need to query for it though?Upvotes: 2
Views: 888
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.
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.
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 existdocument.rootElement
-- deprecateddocument.getElementsByTagName('html')[0]
-- Clunky but robustdocument.body.parentElement
-- Also robustBut perhaps what you want is this:
const $ = document.querySelector.bind(document);
$("html").classList.add("myClass");
Upvotes: 4