How to select <html> element using pure javascript?

Viewed 947

I want to get the element using javascript without using its ID( html id="somethin" ) or a class.

Something like.....

var whatIWantedToSelect = document.html;

OR Something like.....

var whatIWantedToSelect = document.getElementsByTagName('html')[0];

Please, see the below picture to see the exact DOM element that I want to access via javascript.

The DOM element that I want to select

3 Answers

var whatIWantedToSelect = document.html;

The HTML element is the document.documentElement.

var whatIWantedToSelect = document.getElementsByName('html')[0];

getElementsByName matches elements by their name attribute. You are looking for getElementsByTagName.

You can use getElementsByTagName function as follows:

let html = document.getElementsByTagName('html')[0];
console.log(html);
html.addEventListener("click",function(){
     console.log("clicked")
})

html.click();
<html></html>

Related