大多数 DOM 查询方法在 Document
和 Element
上都可用。例如,
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.0 和 1.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 +0000Remove 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/