Vanilla JS Component
by jacobwsmith
HTML
<!-- index.html -->
<h1>My App</h1>
<div class="card">Top level card</div>
<!-- Use the custom element like a regular HTML tag -->
<my-component></my-component>
<hr/>
<my-component></my-component>
JavaScript
// my-component.js
// 1. Define the new component by extending HTMLElement
class MyComponent extends HTMLElement {
constructor() {
super(); // Always call super() first in constructor
// Create a shadow root to encapsulate the component's DOM and styles
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
// This runs when the element is added to the DOM
this.render();
}
render() {
// Example: Create and append elements to the shadow DOM
const container = document.createElement('div');
container.innerHTML = `
<style>
.card {
border: 1px solid #ccc;
padding: 15px;
margin: 10px;
border-radius: 5px;
background-color: #f9f9f9;
}
h3 {
color: blue;
}
</style>
<div class="card">
<h3>Hello from my component v2!</h3>
<p>This is a simple vanilla JS component.</p>
</div>
`;
this.shadowRoot.appendChild(container);
}
}
// 2. Register the custom element
customElements.define('my-component', MyComponent);