David Alsh
David Alsh

Reputation: 7685

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)

Upvotes: 2

Views: 88

Answers (2)

Intervalia
Intervalia

Reputation: 10975

I agree with @Supersharp's answer. Here is an alternate solution without the need of <template>.

class MyComponent extends HTMLElement {
    constructor() {
        super()
        const div = document.createElement('div')
        div.innerHTML = 'Hi'
        this.attachShadow({ mode: 'open' }).appendChild(div)
    }
}
customElements.define('my-component', MyComponent)
<my-component></my-component>

Or you can do it by just using innerHTML of the shadowRoot:

class MyComponent extends HTMLElement {
    constructor() {
        super()
        this.attachShadow({ mode: 'open' }).innerHTML = "<div>Hi</div>";
    }
}
customElements.define('my-component', MyComponent)
<my-component></my-component>

Upvotes: 1

Supersharp
Supersharp

Reputation: 31229

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

Upvotes: 5

Related Questions