鉴于此< template>:
<template id="my-template">
<h1 id="h">Hello!</h1>
</template>
和JS:
var t = document.querySelector("#my-template");
var h = t.content.querySelector("h1");
h.outerHTML = "<h3>AAAAAAAAAAAAAA</h3>";
有趣的是它在FireFox和Edge中有效,但在Chrome中,outerHTML需要父元素,否则它会在控制台(https://chromium.googlesource.com/chromium/blink/+/master/Source/core/dom/Element.cpp#2528)中抛出错误:
<template id="my-template">
<div>
<h1 id="h">Hello!</h1>
</div>
</template>
见https://jsfiddle.net/q5fmn186/11/
我的问题是,Chrome行为是正确的吗?应该在< template>中设置outerHTML不起作用直接孩子?为什么其他网络浏览器不会将其视为错误?
最佳答案 其他Web浏览器不会将其视为错误,因为它们遵循
DOM Parsing and Serialization W3C Candidate Recommendation(这还不是标准):
On setting [outerHTML], the following steps must be run:
- Let parent be the context object’s parent.
- If parent is null, terminate these steps. There would be no way to obtain a reference to the nodes created even if the remaining steps were run.
- If parent is a Document, throw a DOMException with name “NoModificationAllowedError” exception.
- If parent is a DocumentFragment, let parent be a new Element with body as its local name, the HTML namespace as its namespace, and the context object’s node document as its node document.
- Let fragment be the result of invoking the fragment parsing algorithm with the new value as markup, and parent as the context element.
- Replace the context object with fragment within the context object’s parent.
< template>的内容属于DocumentFragment类型(步骤4),但Chrome和Safari将其视为文档(步骤3)(在此情况下).