Cookbook Home ~ alanwsmith.com ~ links ~ podcast ~ twitter

Web Component - Use Internal Elements

Deatils

HTML

Here's the HTML:

<wrapper-component>
  <option value="the"></option>
  <option value="quick"></option>
  <option value="fox"></option>
</wrapper-component>

JavaScript

And this is the JavaScript

class WrapperComponent extends HTMLElement {
    constructor() {
        super()
        this.attachShadow({ mode: 'open' })

        this.upperCasedOptions = []
        this.output = document.createElement('span')

        const loadOptions = () => {
            const options = this.getElementsByTagName('option')
            for (const option of options) {
                this.upperCasedOptions.push(option.value.toUpperCase())
            }
            this.output.innerText = this.upperCasedOptions.join(' ')
        }

        this.shadowRoot.append(this.output)
        document.addEventListener('DOMContentLoaded', loadOptions)
    }
}

customElements.define('wrapper-component', WrapperComponent)

Output Example

Notes

TODO

References