<body>
<attribute-element id="element" data-content="Initial content"></attribute-element>
<button onclick="buttonClicked()">Click to change attribute</button>
<script>
class AttributeElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `<p>Attribute Example: <span id="content"></span></p>`;
}
static get observedAttributes() {
return ['data-content'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'data-content') {
this.shadowRoot.getElementById('content').textContent = newValue;
}
}
set content(value) {
this.setAttribute('data-content', value);
}
get content() {
return this.getAttribute('data-content');
}
}
customElements.define('attribute-element', AttributeElement);
function buttonClicked() {
alert('button clicked!');
const ourCustomElement = document.getElementById('element');
ourCustomElement.content = 'New content';