// ES6 class class HelloWorld extends HTMLParagraphElement { // constructor is called when the element is displayed constructor() { super(); // create a shadow dom const shadow = this.attachShadow({ mode: "closed" }); // create a span element const text = document.createElement("span"); // set the content to 'Hello World' text.textContent = 'Hello World'; // insert our created element into our shadow DOM, causing it to appear shadow.appendChild(text); } } // make sure that the <hello-world></hello-world> // or simply <hello-world /> is recognised as this element customElements.define("hello-world", HelloWorld, { extends: "p" });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Hello World</title> <style> article { max-width: 38rem; padding: 2rem; margin: auto; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; } </style> </head> <body> <article> <h1>Hello World of Web Components</h1> <p>This is a web components demo! Now let's go:</p> <!-- DANGER --> <!-- WEB COMPONENTS --> <!-- BEYOND THIS POINT --> <hello-world></hello-world> </article> </body> </html>