Skip to content

Instantly share code, notes, and snippets.

@semagarcia
Created April 14, 2021 19:10
Show Gist options
  • Save semagarcia/7df05a274880ca8740c628b6ecb91e2c to your computer and use it in GitHub Desktop.
Save semagarcia/7df05a274880ca8740c628b6ecb91e2c to your computer and use it in GitHub Desktop.
Hello World Web Component example with plan JavaScript (without additional libraries)
<script>
// JavaScript code for creating "my-web-component" custom element
// using HTMLElement as base class from which to extend
customElements.define('my-web-component', class extends HTMLElement {
constructor() {
super();
// Find an HTML snippet (template used by WebComponent)
const template = document.querySelector('#myTpl');
const templateContent = template.content;
// Attach a shadow root to <my-web-component>
const shadowRoot = this.attachShadow({ mode: 'open' });
// Create a style tag for containing some CSS styles
const style = document.createElement('style');
style.textContent = 'h1 { color: rebeccapurple; margin: 16px; }';
// Insert (append) previous defined styles into shadow DOM
shadowRoot.appendChild(style);
// Clone node containing the template and insert into shadow DOM
shadowRoot.appendChild(templateContent.cloneNode(true));
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment