JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)
How do you create custom HTML element?
The creation of custom HTML elements involves two main steps,
- Define your custom HTML element: First you need to define some custom class by extending HTMLElement class.
After that define your component properties (styles,text etc) using
connectedCallbackmethod. Note: The browser exposes a function calledcustomElements.defineinorder to reuse the element.
javascript
class CustomElement extends HTMLElement {
connectedCallback() {
this.innerHTML = "This is a custom element";
}
}
customElements.define("custom-element", CustomElement);
- Use custom element just like other HTML element: Declare your custom element as a HTML tag.
javascript
<body>
<custom-element>
</body>