Element Types
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
Web Components โฉ Custom Elements โฉ
MDN โฉ CSS โฉ is attribute
Google โฉ Extending native HTML elements
autonomous custom elements:
โall-newโ elements, extending the abstract HTMLElement
class.
customized built-in elements:
extending built-in elements (such as <p>
, <a>
, <br>
)
๐พ replit.com
๐พ fancy-button, bigger-image
<!-- web component -->
<my-component></my-component>
// 1. extend built-in element
class FancyButton extends HTMLButtonElement {
constructor(){...}
}
// 2. register new tag
customElements.define('fancy-button', FancyButton, {extends: 'button'});
// 3. create with `document.createElement()`
let button = document.createElement('button', {is: 'fancy-button'});
button.textContent = 'Fancy button!';
button.disabled = true;
document.body.appendChild(button);
// 4. create with `new`
let button = new FancyButton();
button.textContent = 'Fancy button!';
button.disabled = true;
<!-- 3. use `is` attribute -->
<p is="my-paragraph">some text</p>
// โญ๏ธ 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);