In this article we're going to show you how to select the root element in a document. The root element may differ in different types of documents. For example, in an HTML document the root element is the html
tag, in an RSS document the root element is the rss
tag, etc.
Using document.documentElement
document.documentElement
returns the root element of the document
. For example:
console.log(document.documentElement);
Using document.querySelector()
We can use the :root
selector, which matches the root element of the document
, with document.querySelector()
in the following way to get the root element:
console.log(document.querySelector(':root'));
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.