最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to select <html> element using pure javascript? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Jun 14, 2020 at 17:24 Lakshitha Kanchana asked Jun 14, 2020 at 17:18 Lakshitha KanchanaLakshitha Kanchana 1,2352 gold badges18 silver badges38 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

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.

The root <html> element is available as document.documentElement. So there is no need to select it by tag name (which would have worked too, but you had getElementsByName instead of getElementsByTagName).

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement

var whatIWantedToSelect = document.documentElement

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>

发布评论

评论列表(0)

  1. 暂无评论