html - 为什么 DOM 不阻止将 <div> 附加到 <p> 元素中?

标签 html dom specifications

这是一个更普遍的问题的示例,涉及 HTML5 解析器和 DOM API 之间的关系。 HTML 中不允许的某些内容显然与 DOM API 无关,因此您可以通过 DOM 创建“不允许的”HTML 情况。

例如根据 HTML5 规范,the p element具有仅“短语内容”的内容模型。现在"content model"是“必须包含哪些内容作为元素的子元素和后代的规范描述。”和 "phrasing content"基本上是文本和“段落内”标记,例如链接和跨度,而不是 div 元素。

事实上,如果我制作一个 HTML 文档或导致 HTML 代码片段像这样被解析,div 就会被强制“取消嵌套”:

var containerEl = document.createElement('body');
containerEl.innerHTML = "<p><div></div></p>";
console.log(containerEl.innerHTML); // -> "<p></p><div></div><p></p>"

似乎在解析过程中,“原始”段落被分成两部分,中间有 div。

但是,这段代码让我可以毫无问题地将 div 插入到 p 中:

 let pEl = document.createElement('p'),
     divEl = document.createElement('div');
 pEl.appendChild(divEl);
 console.log(pEl.outerHTML);     // -> "<p><div></div></p>"

现在 DOM Level 3 规范表示 .appendChild method如果插入了错误的节点“类型”,则会引发 DOMException:

HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node

我怀疑在这种情况下“类型”可能更多地指的是,例如您无法将 Element 节点附加为 Text 节点的子节点。

标准中是否有任何内容澄清了此处的行为,承认存在差异?通过 JavaScript 创建 DOM 层次结构(在解析 HTML 时不允许)会产生什么后果?

最佳答案

Is there anything in the standard that clarifies the behavior here, acknowledging the discrepancy?

是的,html5 standard提到 DOM != HTML != XHTML

1.8 HTML vs XML syntax

The DOM, the HTML syntax, and the XML syntax cannot all represent the same content. For example, namespaces cannot be represented using the HTML syntax, but they are supported in the DOM and in the XML syntax. Similarly, documents that use the noscript feature can be represented using the HTML syntax, but cannot be represented with the DOM or in the XML syntax. Comments that contain the string "-->" can only be represented in the DOM, not in the HTML and XML syntaxes.


What are the consequences to making a DOM hierarchy via JavaScript that's not allowed when parsing HTML?

取决于你在做什么。它可能会导致跨浏览器的行为不一致。它可能会带来令人惊讶的造型。否则可能会导致内容无法呈现。例如。插入 <p>进入<select>只是不会让它渲染。

直接节点操作 API(例如 appendChild )将显示与 fragment parsing algorithms 相比不同的行为(例如 insertAdjacentHTMLinnerTHML )因为后者本质上是通过文档解析器运行文本,而 perform adjustments同时根据 HTML-specific rules 创建 DOM 树来自文本,而节点操作 API 更通用,不知道此类调整。

关于html - 为什么 DOM 不阻止将 <div> 附加到 <p> 元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45382707/

相关文章:

javascript - 在 DOM 中添加/删除多个元素的最快方法

java - 将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么?

c# - C# 规范是否禁止基于默认参数的类型推断?

Java SE 规范 |S|象征

javascript - 重置进度条值 jQuery

javascript - 使用 bxslider,在调整浏览器大小之前没有幻灯片?

javascript - 如何访问使用外部样式表的 javascript 对象的样式属性?

Java:使用 DOM 和 unescapeHtml4() 生成 XML

html - 限制在距输入字段末尾一定距离处打字

html - 将 <html> 嵌套在 <html> 中是否有效?