Search code examples
javascriptweb-componentshadow-domhtml5-template

Template tag created using JS doesn't appear when appended to shadow inside web component


I would expect the following code to create an element which contains a div with the text "Hi" in it.

The element appears in the inspector, but no text is visible on the screen.

When I change the template from a template to a div the text shows up. What have I done wrong here?

class MyComponent extends HTMLElement {
    constructor() {
        super()

        const shadowRoot = this.attachShadow({ mode: 'open' })
        const template = document.createElement('template')
        const div = document.createElement('div')

        div.innerHTML = 'Hi'
        template.appendChild(div)

        shadowRoot.appendChild(template.content)
    }
}
customElements.define('my-component', MyComponent)

Solution

  • <template> is a special element.

    Append some HTML elements through its content property:

    template.content.appendChild(div)
    

    or add the HTML code via its innerHTML property:

    template.innerHTML = '<div>Hi</div>'