Search code examples
javascriptweb-component

Vanilla JS web component including <head> and <body>


Is it possible to include head and body as elements of a web component?

I tried the example below, but web-html is placed inside body, and head is empty:

index.html:

<!doctype html>
<html>
    <web-html></web-html>
    <script type="module" src="html.js"></script>
</html>

html.js:

customElements.define('web-html', class extends HTMLElement {
    constructor() {
        super();
        const template = document.createElement('template');
        template.innerHTML = `
            <head>
                <meta charset="utf-8" />
                <title> Index </title>
            </head>
            <body>
                <slot> ... </slot>
            </body>
        `;
        const shadowRoot = this.attachShadow({mode:'open'});
        shadowRoot.appendChild(template.content.cloneNode(true));
    };
});

Solution

  • A Custom Element must be included either in the <head> or in a <body> element. Therefore it should not contain any <head> or <body> element.

    As a consequence, if you want to include content on both <head> and <body> you'll need do it in a different way: with document.head.appendChild() for example.

    Moreover, <head> and <body> must be direct children of <html> so you cannot include them in a custom element.