Lesson 33 of 55
javascriptWeb Components – Custom Elements, Shadow DOM & Templates
13 mins
Course progress60%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 33 of 55
javascript13 mins
Keep these ideas in mind as you work through the lesson.
Custom elements let you define new HTML tags.
class MyButton extends HTMLElement {
constructor(){
super();
const tmpl = document.getElementById('tpl').content;
this.attachShadow({mode:'open'}).appendChild(tmpl.cloneNode(true));
}
}
customElements.define('my-button', MyButton);
Shadow DOM encapsulates markup and styles.
<template id="tpl">
<style>button{background:#0066cc;color:#fff;padding:0.5rem;}</style>
<button><slot></slot></button>
</template>
<my-button> like any native element.<my-button>Click me</my-button>