CodeLab
Tutorials For Everyone
Run
<!DOCTYPE html> <html> <head> <title>HTML Custom Tags Using Template Method Example</title> </head> <body> <h2>HTML Custom Tags/Elements</h2> <p>Below is an example in which we defined and utilized a custom HTML tag. On left side of the CodeLab editor, you can check the definition of the custom HTML element. Using this custom tag, we can insert notes with border and red color scheme.</p> <p>Try Modifying the code and check the reuslts yourself.</p> <template id="add-red-note-temp"> <style> div { padding: 20px; font-size: 20px; background: #fdecea; color: #aa2e25; border-radius: 10px; border-left: 10px solid #aa2e25; box-shadow: 0 0 2px #aa2e25; } </style> <div> <span></span> </div> </template> <add-red-note text="This Note is Red. It is added using HTML custom elemnts template method."></add-red-note> <br /> <add-red-note text="Another Note added with custom HTML tags."></add-red-note> <script> const template = document.getElementById("add-red-note-temp"); if (template) { class addRedNote extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template.content.cloneNode(true)); this._text = this.shadowRoot.querySelector("span"); } static get observedAttributes() { return ["text"]; } attributeChangedCallback(name, oldValue, newValue) { if (name === "text") { this._text.textContent = newValue; } } } customElements.define("add-red-note", addRedNote); } </script> </body> </html>