【问题标题】:Why XMLElement interface is not part of Web APIs?为什么 XMLElement 接口不是 Web API 的一部分?
【发布时间】:2021-08-09 01:53:09
【问题描述】:

MDN Web APIs Specifications中,有HTMLDocumentXMLDocumentHTMLElement接口。因此我也希望看到一个 XMLElement 接口。

但是,没有看到 XMLElement 接口。因此,我进行了此调查,以了解模式停止的原因。

【问题讨论】:

  • 快速浏览一下规范,它们在这些文档中解释/应用元素的方式只有区别,但实际的 API 和接口看起来完全一样,因此似乎仅此而已而不是一个标记来告诉浏览器使用什么。此外,关于 XMLDocument 的 MDN 是旧的、简短的,并提到:“它继承自通用 Document,并没有向其添加任何特定的方法或属性:尽管如此,几种算法对这两种类型的文档的行为不同。”

标签: javascript dom webapi


【解决方案1】:

您希望XMLElement 接口有什么具体行为?

我们只为确实需要特定行为的元素创建新接口,而简单的 XML 元素则没有,它们被 Element 接口完全覆盖。

关于您关于setAttribute 的问题,in HTML the method 将查看定义元素的名称空间以及它所属的文档。

例如,您可以在 HTML 文档中包含 SVG 等外来元素,但它们的属性不会小写。

const svg = document.querySelector("svg");
svg.setAttribute("viewBox", "0 0 1 1");

console.log("is HTMLDocument", document instanceof HTMLDocument);
console.log("has lower case attribute 'viewbox'", svg.hasAttribute("viewbox"));
console.log("has camel case attribute 'viewBox'", svg.hasAttribute("viewBox"));
<svg></svg>

请注意,由于这个 元素需要特定的行为,它有自己的SVGSVGElement 接口。

或者您可以在 XMLDocument 中包含 HTMLElements,它也不会小写:

const XML_Doc = document.implementation.createDocument(null, "");
const HTML_elem = document.createElement("div");
XML_Doc.append(HTML_elem);
HTML_elem.setAttribute("myAttribute", "");

console.log("is XMLDocument", XML_Doc instanceof XMLDocument);
console.log("is HTMLElement", HTML_elem instanceof HTMLElement);
console.log("has lower case attribute 'myattribute'", HTML_elem.hasAttribute("myattribute"));
console.log("has camel case attribute 'myAttribute'", HTML_elem.hasAttribute("myAttribute"));

在这里使用不同的界面无济于事。

还要注意 XMLDocument 接口的存在是因为它使用有一些独特的方法/属性。它不再是,但完全删除界面可能对网络不安全,某些网站可能依赖它。

【讨论】:

    猜你喜欢
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2017-07-22
    • 2019-08-25
    相关资源
    最近更新 更多