Source Code: (back to article)
<div>
<script>
class AttributeComponent extends HTMLElement {
static get observedAttributes() {
return ['data-text'];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = '<p></p>';
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'data-text') {
this.shadowRoot.querySelector('p').textContent = newValue;
}
}
}
customElements.define('attribute-component', AttributeComponent);
</script>
<attribute-component data-text="Initial text"></attribute-component>
<script>
const element = document.querySelector('attribute-component');
setTimeout(() => {
element.setAttribute('data-text', 'Updated text');
}, 2000);
</script>
</div>