Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Last active March 14, 2025 21:01
Show Gist options
  • Save henriquegogo/ea84886e9d98a97332b70d578a36fc8c to your computer and use it in GitHub Desktop.
Save henriquegogo/ea84886e9d98a97332b70d578a36fc8c to your computer and use it in GitHub Desktop.
Custom Elements from Template. Use <slot /> for variables.
document.querySelectorAll('template[id]').forEach(({id, content}) =>
customElements.define(id, class extends HTMLElement {
constructor() {
super().attachShadow({mode: 'open'}).appendChild(content.cloneNode(true));
[...this.attributes].forEach(({name, value}) => {
const span = document.createElement('span');
this.appendChild(Object.assign(span, {slot: name})).textContent = value;
this.removeAttribute(name)
this.shadowRoot.querySelectorAll(`[${name}]`).forEach(el =>
!el.getAttribute(name) && el.setAttribute(name, value));
});
}
}));
<script defer src="./script.js"></script>
<x-button onclick="console.log('here')" label="Button 1">Click here</x-button>
<x-button onclick="console.log('now')" label="Button 2">Click now!</x-button>
<template id="x-button">
<style>label { display: block; }</style>
<label><slot name="label"></slot>
<button onclick><slot></slot></button>
</label>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment