Can I access a live region in light DOM from shadow DOM?

posted on

Back to overview

Yes.

There's nothing much to say except that accessing the document from within a component's shadow DOM is possible.

<the-button></the-button>
<output></output>
class TheButton extends HTMLElement {
constructor() {
super()
this.shadow = this.attachShadow({ mode: "open" })

const button = document.createElement("button")
button.textContent = 'Random name'
button.addEventListener('click', this._updateLiveRegion)

this.shadow.append(button)
}

_updateLiveRegion( ) {
const names = ['Luffy', 'Nami', 'Zoro', 'Usopp', 'Sanji']
const randomName = names[Math.floor(Math.random() * names.length)]
document.querySelector('output').textContent = randomName
}
}

customElements.define("the-button", TheButton)

Back to overview