Search code examples
web-component

html and body tags inside template tag


I have a custom element and I would like to populate it with DOM from template tag. Everything seems to be inserted into custom element except for html and body tags. Does that mean that html and body tags are not allowed inside custom elements? Here is my code

<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>

Solution

  • Yes.

    The root node of an HTML5 document must be the <html> element. Child nodes of an <html> element must be the <head> and <body> elements.

    Actually you can omit them, but then they are implied.

    In your document, if you don't specify the <html>, <head> and <body> elements, they will be added anyway by the browser, and the root nodes you defined will be added to the <head> or <body> depending on their type and on their position in the page:

    • <link>, <meta>, <script>... inside the <head> if they are at the beginning of the document.

    • <div>, <span>, <section> and Custom Elements inside the <body>.

    • all subsequent elements inside the once an element has beed inserted.


    The content model of a Custom Element is of type Flow, Phrasing or Paplable content. That means it must be inserted inside a <body> element.

    <html> and <body> inside a Custom Element are not valid and ignored.