【发布时间】:2019-01-18 16:44:52
【问题描述】:
大多数 DOM 查询方法在 Documents 和 Elements 上都可用。例如,
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 兼容性防止
getElementById()方法暴露在元素上
W3C DOM4 推荐 is a bit more specific:
getElementById()方法不适用于与旧版本 jQuery 兼容的元素。如果某个版本的 jQuery 消失了,我们也许可以支持它。
但是,我仍然很难理解问题可能是什么。这种方法的存在如何对 jQuery 或其他库的行为产生不利影响?
我尝试查看旧版本的 jQuery(例如 1.0.0 和 1.7.0),看看他们对 getElementById 的任何使用是否暗示了为什么这可能是一个问题。我看到getElementById 曾经在一些较旧的浏览器中存在错误,但他们检测到这一点并转而使用可靠的手动实现。我看不到任何可以在元素上调用它并导致错误的地方。这种兼容性问题从何而来?
【问题讨论】:
-
因为 id 值在整个文档中必须是唯一的,这有什么意义呢?
-
可能只有一个元素,但我可能只对它存在于文档的特定子树中感兴趣。
-
@Pointy 我已经引用了这两个规范的兼容性问题,所以告诉我这是因为它毫无意义似乎不正确。
-
我不知道旧版本的 jQuery 如何或为什么会引起规范委员会的关注。
-
@Pointy:因为引入
Element#getElementById会破坏使用该版本 jQuery 的现有网站,至少在 2013 年显然已广泛部署。
标签: javascript jquery dom compatibility specifications