Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
Created August 17, 2022 08:36
Show Gist options
  • Save ZacharyL2/089765ccd34cecd3f25cfe6a42726ea0 to your computer and use it in GitHub Desktop.
Save ZacharyL2/089765ccd34cecd3f25cfe6a42726ea0 to your computer and use it in GitHub Desktop.
<custom-button backgroundColor="red"></custom-button>
<script>
const template = `
<style>
button {
background-color: blue;
color: #fff;
}
</style>
<button>Click</button>
`;
function str2DOM(str) {
return document.createRange().createContextualFragment(str);
}
class CustomButton extends HTMLElement {
constructor() {
super();
this.appendChild(str2DOM(template));
this.querySelector('button').style.backgroundColor =
this.getAttribute('backgroundColor');
}
}
window.customElements.define('custom-button', CustomButton);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment