Skip to content

Instantly share code, notes, and snippets.

@duffleit
Created July 2, 2019 11:10
Show Gist options
  • Save duffleit/514b225e39cd95467789926d73eb2748 to your computer and use it in GitHub Desktop.
Save duffleit/514b225e39cd95467789926d73eb2748 to your computer and use it in GitHub Desktop.
UserWidget WebComponent
<script>
class UserWidget extends HTMLElement {
static get observedAttributes() {
return ['name'];
}
constructor(){
super();
this.attachShadow({mode:'open'});
this.shadowRoot.innerHTML = '<div>NO NAME</div>';
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (oldVal !== newVal) {
this.shadowRoot.firstChild.innerHTML = newVal;
}
}
get userName() {
return this.getAttribute('name');
}
set userName(name) {
this.setAttribute('name', name);
}
}
customElements.define('user-widget', UserWidget);
</script>
<user-widget name="Maximilian"></user-widget>
<user-widget name="Susanne"></user-widget>
<user-widget name="Andreas"></user-widget>
<script>
function changeUserWidgetsToUpperCase(){
var elements = document.getElementsByTagName('user-widget')
Array.from(elements).forEach(widget => {
widget.userName = widget.userName.toUpperCase();
})
}
</script>
<button onClick="changeUserWidgetsToUpperCase()">to uppercase</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment