Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Last active March 14, 2025 21:01
Show Gist options
  • Select an option

  • Save henriquegogo/ea84886e9d98a97332b70d578a36fc8c to your computer and use it in GitHub Desktop.

Select an option

Save henriquegogo/ea84886e9d98a97332b70d578a36fc8c to your computer and use it in GitHub Desktop.
Custom Elements from Template. Use <slot /> for variables.
document.addEventListener('DOMContentLoaded', () => {
const createCustomElement = content => class extends HTMLElement {
constructor() {
super().attachShadow({mode: 'open'}).appendChild(content.cloneNode(true));
[...this.attributes].forEach(({name, value}) => this.appendChild(
Object.assign(document.createElement('span'), {slot: name})
).textContent = value);
}
};
document.querySelectorAll('template[id]').forEach(({id, content}) =>
customElements.define(id, createCustomElement(content)));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment