html 和模板标签内的正文标签

html and body tags inside template tag

我有一个自定义元素,我想用模板标签中的 DOM 填充它。除了 html 和 body 标签外,所有内容似乎都已插入到自定义元素中。这是否意味着自定义元素中不允许使用 html 和 body 标签?这是我的代码

<template id="legacy-code-template">
<style>
  body {
    background:red;
  }
</style>
<html><body><p>Sample text</p></body></html>
</template>
<legacy-code></legacy-code>
<script>
    class LegacyCode extends HTMLElement {
        constructor() {
            super();

            const template = document
                .getElementById('legacy-code-template')
                .content;
            const shadowRoot = this.attachShadow({mode: 'open'})
                .appendChild(template.cloneNode(true));
        }
    }

    customElements.define('legacy-code', LegacyCode);
</script>

是的。

HTML5 文档的根节点必须是 <html> 元素。 <html> 元素的子节点必须是 <head><body> 元素。

实际上 you can omit them,但它们是 隐含的

在你的文档中,如果你不指定<html><head><body>元素,浏览器无论如何都会添加它们,并且你定义的根节点将被添加到 <head><body> 中,具体取决于它们的类型和它们在页面中的位置:

  • <link><meta><script>... 如果它们位于文档的开头,则在 <head> 内。

  • <div><span><section><body> 内的自定义元素。

  • 插入元素后所有后续元素。


content model of a Custom Element is of type Flow, Phrasing or Paplable内容。这意味着它必须插入到 <body> 元素中。

自定义元素中的

<html><body> 无效并被忽略。