The Case for Custom Elements: Part 1
The Case for Custom Elements: Part 1 – Dev Channel – Medium by Rod Dodson
Custom Elements:
- Let you define your own HTML tag with bundled JS behavior
- Trigger lifecycle callbacks
- Automatically “upgrade” your tag when inserted in the document
/* my-element.js */
class MyElement extends HTMLElement {
// This gets called when the HTML parser sees your tag
constructor() {
super(); // always call super() first in the ctor.
this.msg = 'Hello, World!';
}
// Called when your element is inserted in the DOM or
// immediately after the constructor if it’s already in the DOM
connectedCallback() {
this.innerHTML = `<p>${this.msg}</p>`;
}
}
// This registers your new tag and associates it with your class
window.customElements.define('my-element', MyElement);
Then you can use in your DOM:
<body>
<my-element></my-element>
<script src="my-element.js"></script>
</body>