How to Select the Document Root Element With JavaScript?

Learn different ways of selecting the root element using JavaScript

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'));

Hope you found this post useful. It was published . Please show your love and support by sharing this post.