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

标签 javascript jquery dom compatibility specifications

大多数 DOM 查询方法在 DocumentElement 上都可用。例如,

console.assert(
  document.getElementsByTagName   && document.body.getElementsByTagName &&
  document.getElementsByClassName && document.body.getElementsByClassName &&
  document.querySelector          && document.body.querySelector &&
  document.querySelectorAll       && document.body.querySelectorAll
);

但是,getElementById 仅在 Document 上可用:

console.assert(document.getElementById);
console.assert(document.body.getElementById == undefined);

为什么会这样?


WHATWG DOM 生活标准 tells us that :

Web compatibility prevents the getElementById() method from being exposed on elements

W3C DOM4 推荐 is a bit more specific :

The getElementById() method is not on elements for compatibility with older versions of jQuery. If a time comes where that version of jQuery has disappeared, we might be able to support it.

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

我尝试查看旧版本的 jQuery(例如 1.0.01.7.0),看看它们对 getElementById 的使用是否暗示了为什么这可能是个问题。我看到 getElementById 曾经在一些较旧的浏览器中存在错误,但他们检测到这一点并转而回退到可靠的手动实现。我看不到任何可以在元素上调用它并导致错误的地方。这种兼容性问题从何而来?

最佳答案

https://github.com/w3c/dom 上的 git blame的 master 分支指向:

commit f71d7de304e1ee25573279157dd6ce1c2aa2c4f2
Author: Anne van Kesteren
AuthorDate: Tue Nov 26 13:53:41 2013 +0000
Commit: Anne van Kesteren <annevk@annevk.nl>
CommitDate: Tue Nov 26 13:53:41 2013 +0000

Remove getElementById from Element. 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 assumes that any node it found in the DOM that has a "getElementById" property is a Document node. See https://bugzilla.mozilla.org/show_bug.cgi?id=933193#c17

关于javascript - 为什么 getElementById() 在 Elements 上不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54258205/

相关文章:

javascript Excel.application 过早关闭 Excel

javascript - 矩阵 : get positive value

jQuery Ajax POST 不成功

java - 从 Java 中的 xml 元素读取 CDATA 时出现错误

javascript - Angular JS 将字符串数组传递给指令

javascript - 在 Axios 请求中使用 Promise

javascript - 如何使用另一个文本区域编辑文本区域值?

javax.swing.text.html.HTML 文档按名称获取元素

javascript - React - 如何给每个子组件一个唯一的引用?

javascript - 淡入一系列 div 然后淡出前一个