为什么getElementById()在Elements上不可用?

6 javascript jquery compatibility dom specifications

Documents和Elements 都可以使用大多数DOM查询方法。例如,

console.assert(
  document.getElementsByTagName   && document.body.getElementsByTagName &&
  document.getElementsByClassName && document.body.getElementsByClassName &&
  document.querySelector          && document.body.querySelector &&
  document.querySelectorAll       && document.body.querySelectorAll
);
Run Code Online (Sandbox Code Playgroud)

但是,getElementById仅适用于Document

console.assert(document.getElementById);
console.assert(document.body.getElementById == undefined);
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?


WHATWG DOM生活标准告诉我们

Web兼容性可防止该getElementById()方法在元素上公开

W3C DOM4建议更加具体

getElementById()方法不在与jQuery较旧版本兼容的元素上。如果那个版本的jQuery消失的时候到了,我们也许可以支持它。

但是,我仍然很难理解问题可能是什么。这种方法的存在如何对jQuery或其他库的行为产生不利影响?

我尝试浏览过旧版本的jQuery(例如1.0.01.7.0),以查看是否使用了getElementById提示来说明这可能是个问题。我看到getElementById以前在某些较旧的浏览器中存在错误,但是它们检测到该错误并转而使用可靠的手动实现。我看不到在元素上可能会调用它并导致错误的任何地方。这种兼容性问题从何而来?

Ry-*_*Ry- 13

git blamehttps://github.com/w3c/dom的主分支点:

提交f71d7de304e1ee25573279157dd6ce1c2aa2c4f2
作者:Anne van Kesteren作者
日期:2013年11月26日星期二13:53:41 +0000
提交:Anne van Kesteren <annevk@annevk.nl>
提交日期:11月26日星期二13:53:41 2013 +0000

从Element中删除getElementById。https://www.w3.org/Bugs/Public/show_bug.cgi?id=23860

链接的错误描述了jQuery 1.2.5 + 1.2.6(1.2.x?)的影响:

jQuery 1.2.5假定在DOM中找到的任何具有“ getElementById”属性的节点都是Document节点。参见https://bugzilla.mozilla.org/show_bug.cgi?id=933193#c17