Last active
March 14, 2025 21:01
-
-
Save henriquegogo/ea84886e9d98a97332b70d578a36fc8c to your computer and use it in GitHub Desktop.
Custom Elements from Template. Use <slot /> for variables.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}); | |
} | |
})); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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