Web Component - Use Internal Elements
Deatils
- This example accesses <option> elements inside the component on the main page
- Data is pulled out of the <option> elements, updated and delivered back for display in upper case
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
- Access to the <option> elements is via `.getElementsByTagName('option')` run on the `.this` object
- With some browsers (e.g. Chrome) the `.getElementsByTagName('option')` call is fired when the opening tag of the component (e.g. <wrapper-component>) is hit. At that point, the <option> tags don't exist so it returns and empty list (even though they sometimes show up in the console)
- There is a note here about one way to deal with that.
- I'm using a different technique which is to wait until the DOMContentLoaded event before trying to access the <option> tags. It's working in my test cases.
- One aspect of that approach is that potentially nothing would should up until the event fires and the data is load which could cause a content shift. A soltuion for that would be to stub in whatever area is needed on the first locat of the element then updated it when everything is available
TODO
- Write up a post about using DOMContentLoaded to get at elements inside a custom component
References
- Answer to: Iterate over HTMLCollection in custom element - I'm using a different technique, but this is where I learned about how the `connectedCallback()` event can get fired on the opening tag
- Disccsion on - This is a bunch of discussion about the callback issue linked from the SO answer.