Element Types
Autonomous
// ⭐️ 1. custom web component
class MyComponent extends HTMLElement {
// constructor
constructor() {
// tell HTMLElement to initialize itself.
super();
// get `width`, `height` attributes
const height = this.getAttribute('height') || '100px';
const width = this.getAttribute('width') || '100px';
// create <template> element
const template = document.createElement('template');
template.innerHTML = MyComponent.template(height, width);
// add component to UI
this.appendChild(document.importNode(template.content, true));
}
// template HTML
static template(height, width) {
return `
<style>
.placeholder {
background-color: pink;
width: ${height};
height: ${width};
}
</style>
<div class='placeholder'>Placeholder</div>
`;
}
}
// ⭐️ 2. custom tag <my-component>
// ⭐️⭐️ custom element names must contain a "hyphen".
customElements.define('my-component', MyComponent);Customized Built-in Elments
Last updated