class WordCount extends HTMLParagraphElement {
constructor() {
super();
}
// Element functionality written in here
}Using custom elements / notebook
Using custom elements
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
class PopupInfo extends HTMLElement {
constructor() {
super();
}
// Element functionality written in here
}// Create a class for the element
class MyCustomElement extends HTMLElement {
static observedAttributes = ["color", "size"];
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
console.log("Custom element added to page.");
}
disconnectedCallback() {
console.log("Custom element removed from page.");
}
connectedMoveCallback() {
console.log("Custom element moved with moveBefore()");
}
adoptedCallback() {
console.log("Custom element moved to new page.");
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`Attribute ${name} has changed.`);
}
}
customElements.define("my-custom-element", MyCustomElement);class MyComponent {
// ...
connectedMoveCallback() {
console.log("Custom move-handling logic here.");
}
// ...
}customElements.define("word-count", WordCount, { extends: "p" });customElements.define("popup-info", PopupInfo);<p is="word-count"></p><popup-info>
<!-- content of the element -->
</popup-info>const myRegistry = new CustomElementRegistry();
myRegistry.define(
"my-element",
class extends HTMLElement {
connectedCallback() {
this.textContent = "Hello from scoped registry!";
}
},
);const host = document.createElement("div");
document.body.appendChild(host);
const shadow = host.attachShadow({
mode: "open",
customElementRegistry: myRegistry,
});
// <my-element> is upgraded using myRegistry's definition
shadow.innerHTML = "<my-element></my-element>";const shadow = host.attachShadow({
mode: "open",
customElementRegistry: null, // no registry yet
});
shadow.innerHTML = "<my-element></my-element>";
// Later, associate the scoped registry and upgrade elements
myRegistry.initialize(shadow);<my-host>
<template shadowrootmode="open" shadowrootcustomelementregistry>
<my-element></my-element>
</template>
</my-host>// Create a class for the element
class MyCustomElement extends HTMLElement {
static observedAttributes = ["size"];
constructor() {
super();
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(
`Attribute ${name} has changed from ${oldValue} to ${newValue}.`,
);
}
}
customElements.define("my-custom-element", MyCustomElement);<my-custom-element size="100"></my-custom-element>class MyCustomElement extends HTMLElement {
constructor() {
super();
this._internals = this.attachInternals();
}
get collapsed() {
return this._internals.states.has("hidden");
}
set collapsed(flag) {
if (flag) {
// Existence of identifier corresponds to "true"
this._internals.states.add("hidden");
} else {
// Absence of identifier corresponds to "false"
this._internals.states.delete("hidden");
}
}
}
// Register the custom element
customElements.define("my-custom-element", MyCustomElement);my-custom-element {
border: dashed red;
}
my-custom-element:state(hidden) {
border: none;
}// Create a class for the element
class PopupInfo extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
// Create a shadow root
const shadow = this.attachShadow({ mode: "open" });
// Create spans
const wrapper = document.createElement("span");
wrapper.setAttribute("class", "wrapper");
const icon = document.createElement("span");
icon.setAttribute("class", "icon");
icon.setAttribute("tabindex", 0);
const info = document.createElement("span");
info.setAttribute("class", "info");
// Take attribute content and put it inside the info span
const text = this.getAttribute("data-text");
info.textContent = text;
// Insert icon
let imgUrl;
if (this.hasAttribute("img")) {
imgUrl = this.getAttribute("img");
} else {
imgUrl = "img/default.png";
}
const img = document.createElement("img");
img.src = imgUrl;
icon.appendChild(img);
// Create some CSS to apply to the shadow dom
const style = document.createElement("style");
console.log(style.isConnected);
style.textContent = `
.wrapper {
position: relative;
}
.info {
font-size: 0.8rem;
width: 200px;
display: inline-block;
border: 1px solid black;
padding: 10px;
background: white;
border-radius: 10px;
opacity: 0;
transition: 0.6s all;
position: absolute;
bottom: 20px;
left: 10px;
z-index: 3;
}
img {
width: 1.2rem;
}
.icon:hover + .info, .icon:focus + .info {
opacity: 1;
}
`;
// Attach the created elements to the shadow dom
shadow.appendChild(style);
console.log(style.isConnected);
shadow.appendChild(wrapper);
wrapper.appendChild(icon);
wrapper.appendChild(info);
}
}customElements.define("popup-info", PopupInfo);<popup-info
img="img/alt.png"
data-text="Your card validation code (CVC)
is an extra security feature — it is the last 3 or 4 numbers on the
back of your card."></popup-info>// Create a class for the element
class PopupInfo extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
// Create a shadow root
const shadow = this.attachShadow({ mode: "open" });
// Create spans
const wrapper = document.createElement("span");
wrapper.setAttribute("class", "wrapper");
const icon = document.createElement("span");
icon.setAttribute("class", "icon");
icon.setAttribute("tabindex", 0);
const info = document.createElement("span");
info.setAttribute("class", "info");
// Take attribute content and put it inside the info span
const text = this.getAttribute("data-text");
info.textContent = text;
// Insert icon
let imgUrl;
if (this.hasAttribute("img")) {
imgUrl = this.getAttribute("img");
} else {
imgUrl = "img/default.png";
}
const img = document.createElement("img");
img.src = imgUrl;
icon.appendChild(img);
// Apply external styles to the shadow dom
const linkElem = document.createElement("link");
linkElem.setAttribute("rel", "stylesheet");
linkElem.setAttribute("href", "style.css");
// Attach the created elements to the shadow dom
shadow.appendChild(linkElem);
shadow.appendChild(wrapper);
wrapper.appendChild(icon);
wrapper.appendChild(info);
}
}// Create a class for the element
class ExpandingList extends HTMLUListElement {
connectedCallback() {
// Get ul and li elements that are a child of this custom ul element
// li elements can be containers if they have uls within them
const uls = this.querySelectorAll("ul");
const lis = this.querySelectorAll("li");
// Hide all child uls
// These lists will be shown when the user clicks a higher level container
for (const ul of uls) {
ul.style.display = "none";
}
// Look through each li element in the ul
for (const li of lis) {
// If this li has a ul as a child, decorate it and add a click handler
if (li.querySelectorAll("ul").length > 0) {
// Add an attribute which can be used by the style
// to show an open or closed icon
li.setAttribute("class", "closed");
// Wrap the li element's text in a new span element
// so we can assign style and event handlers to the span
const childText = li.childNodes[0];
const newSpan = document.createElement("span");
// Copy text from li to span, set cursor style
newSpan.textContent = childText.textContent;
newSpan.style.cursor = "pointer";
// Add click handler to this span
const onClick = (e) => {
// next sibling to the span should be the ul
const nextUl = e.target.nextElementSibling;
// Toggle visible state and update class attribute on ul
if (nextUl.style.display === "block") {
nextUl.style.display = "none";
nextUl.parentNode.setAttribute("class", "closed");
} else {
nextUl.style.display = "block";
nextUl.parentNode.setAttribute("class", "open");
}
};
newSpan.addEventListener("click", onClick);
// Add the span and remove the bare text node from the li
childText.parentNode?.insertBefore(newSpan, childText);
childText.parentNode?.removeChild(childText);
}
}
}
}customElements.define("expanding-list", ExpandingList, { extends: "ul" });<ul is="expanding-list">
…
</ul><script src="main.js" defer></script>class Square extends HTMLElement {
// …
constructor() {
// Always call super first in constructor
super();
const shadow = this.attachShadow({ mode: "open" });
const div = document.createElement("div");
const style = document.createElement("style");
shadow.appendChild(style);
shadow.appendChild(div);
}
// …
}function updateStyle(elem) {
const shadow = elem.shadowRoot;
shadow.querySelector("style").textContent = `
div {
width: ${elem.getAttribute("size")}px;
height: ${elem.getAttribute("size")}px;
background-color: ${elem.getAttribute("color")};
}
`;
}class Square extends HTMLElement {
// …
connectedCallback() {
console.log("Custom square element added to page.");
updateStyle(this);
}
// …
}class Square extends HTMLElement {
// …
disconnectedCallback() {
console.log("Custom square element removed from page.");
}
adoptedCallback() {
console.log("Custom square element moved to new page.");
}
// …
}class Square extends HTMLElement {
// …
attributeChangedCallback(name, oldValue, newValue) {
console.log("Custom square element attributes changed.");
updateStyle(this);
}
// …
}class Square extends HTMLElement {
// …
static get observedAttributes() {
return ["color", "size"];
}
// …
}