Javascript 有没有一种不使用标记名就调用HTML元素的方法?

Javascript 有没有一种不使用标记名就调用HTML元素的方法?,javascript,html,Javascript,Html,这是一个简单的问题: 有没有一种方法可以在不使用以下命令的情况下调用HTML元素: document.getElementsByTagName('HTML')[0] 使用JavaScript。要获得身体,您可以执行以下操作: document.body 使用JavaScript有没有更简单的方法呢?您可以参考文档。documentElement: console.log(document.getElementsByTagName('HTML')[0]==document.documentE

这是一个简单的问题: 有没有一种方法可以在不使用以下命令的情况下调用HTML元素:

document.getElementsByTagName('HTML')[0]
使用JavaScript。要获得身体,您可以执行以下操作:

document.body

使用JavaScript有没有更简单的方法呢?

您可以参考
文档。documentElement


console.log(document.getElementsByTagName('HTML')[0]==document.documentElement)您可以向HTML元素添加一个ID,然后使用document.getElementById(“idOfTheElement”)

所有这些都可以用来获取对
元素的引用:


  • document.documentElement
  • document.querySelector('html')
  • document.querySelectorAll('html')[0]
  • document.getElementById('foo')
    -如果设置了
  • document.getElementsByClassName('bar')[0]
    -如果设置了
  • document.getElementsByTagName('html')[0]
  • document.head.parentElement
  • document.body.parentElement
您还可以通过使用
parentElement
parentNode
向上导航,获得对根
元素的引用:

var anyElement = document.getElementById('somethingOtherThanHtml');
var htmlElement = anyElement;
while( htmlElement.tagName != "HTML" ) {
    htmlElement = htmlElement.parentElement;
}

而且
document
也是
window
的成员(事实上,
window
是所有浏览器网页脚本场景中的“根对象”),因此,如果您只有
window
,您可以使用
window.document.documentElement
等(“classname”)


classname表示该标记的类

您可以使用queryselector:

document.querySelector('HTML')

但是,有没有不使用标记名的方法,或者这是唯一的方法?谢谢,尽管
document.documentElement
根本不使用“HTML”标记名..?这就像
document.body
你应该阅读并获得基本知识一样。