简体   繁体   English

设置document.body.outerHTML会创建空头。 为什么?

[英]Setting document.body.outerHTML creates empty heads. Why?

Resetting outerHTML property of document.body has a strange side effect: it adds extra empty <head></head> into the DOM, just before body : 重置document.body outerHTML属性有一个奇怪的副作用:它在DOM中添加额外的空<head></head> ,就在body之前:

 head { display: inline; counter-increment: h; border: 1px solid; } head:last-of-type::after { content: 'Head elements count: ' counter(h); } [onclick]::after { content: attr(onclick); } 
 <button onclick="document.body.outerHTML=document.body.outerHTML"></button> 

All browsers seem to be consistent in this. 所有浏览器似乎都是一致的。 I've been told it is specified to be this way, but was not able to dig up authoritative standards stance about this, not even any mention in discussion archives. 被告知它被指定为这种方式,但是无法在这个问题上挖掘权威的标准立场,甚至在讨论档案中都​​没有提及。 Do you know some background of this, or is there some technical reason it has to be this way? 你知道这方面的背景吗,还是有一些技术原因必须这样? Any idea? 任何想法?

Interesting question. 有趣的问题。 Unfortunately the explanation is buried in the details of the HTML fragment parsing algorithm which is referenced from the definition of outerHTML in the DOM Parsing spec. 遗憾的是,解释隐藏在HTML片段解析算法的细节中,该算法从DOM解析规范中的outerHTML的定义中引用。

You'll need to follow the parser states through very carefully to see why, but in essence it works like this. 您需要非常仔细地遵循解析器状态以查明原因,但实际上它的工作原理与此类似。 With outerHTML, the parser is initialised as if it has just parsed the start tag of the given node's parent. 使用outerHTML,解析器被初始化,就像它刚刚解析了给定节点的父节点的开始标记一样。 For document.body, that's the html element. 对于document.body,这是html元素。

In the HTML parsing algorithm, when an html start tag is parsed, the next thing the parser expects is a head element. 在HTML解析算法中,当解析html开始标记时,解析器期望的下一个是head元素。 But because, in HTML, the start and end tags of the head element are optional, if it doesn't see a head start tag next, it infers one. 但是因为在HTML中,head元素的开始和结束标记是可选的,如果它接下来没有看到head start标记,则它会推断出一个。 So in the case of document.body.outerHTML, the next thing the parser sees is the body start tag, and so creates an empty head element first. 因此,对于document.body.outerHTML,解析器看到的下一件事是body start标记,因此首先创建一个空头元素。

Finally, once the fragment is parsed, the whole lot, including the inferred head element is added to the DOM. 最后,一旦解析了片段,整个批次(包括推断的head元素)就会被添加到DOM中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM