【问题标题】:why document has getElementById method even though it doesnt inherit from Element?为什么文档有 getElementById 方法,即使它不是从 Element 继承的?
【发布时间】:2020-07-24 19:11:07
【问题描述】:

按照 MDN 文档,Element interface 包含搜索 dom 节点的所有方法,例如

  • getElementById
  • getElementsByTagName
  • ...

MDN 还 states Document 直接继承自 Node。 不是来自 Element。

那么,为什么 Document 包含所有这些 Element 方法(以及来自 ParentNode 接口的方法)? MDN 只是没有更新规格还是我遗漏了什么?

【问题讨论】:

  • 它有自己的方法,它不继承它:developer.mozilla.org/en-US/docs/Web/API/Document/…
  • Element 接口包含getElementById().getElementById() 方法作为 Element 方法没有意义,因为它本质上是文档的全局
  • @Barmar 似乎德国 MDN 不是最新的。它在 en-US 中列为方法,但在 de 中没有
  • @Pointy 猜我需要编辑标题和文本。谢谢指出。 //编辑:没关系,因为它在答案中被引用,我让它保持原样

标签: javascript dom domdocument


【解决方案1】:

两者 Document.prototypeElement.prototype 都有 getElementsByTagName。一个不是从另一个继承的——它们是完全独立的函数(不直观):

console.log(
  Element.prototype.hasOwnProperty('getElementsByTagName'),
  Document.prototype.hasOwnProperty('getElementsByTagName'),
  Element.prototype.getElementsByTagName === Document.prototype.getElementsByTagName,
  Document.prototype.hasOwnProperty('getElementById'),
  Element.prototype.hasOwnProperty('getElementById'),
);

Element.prototype没有getElementById

ParentNode 接口是一个抽象规范,而不是您可以在某处检查的实际 Javascript 对象。 Element.prototypeDocument.prototype 都实现了它,但它们是通过将 ParentNode 方法直接放在它们的原型上来实现的。 (ParentNode 根本不是和 Node 一样)

【讨论】:

  • 我知道 ParentNode 只是一个接口,由文档和元素实现。然而;反正我一直在想。感谢您的回答 - 帮了很多忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 2011-12-26
  • 2014-06-09
相关资源
最近更新 更多