Skip to content

Instantly share code, notes, and snippets.

@schafeld
Last active May 21, 2025 20:04
Show Gist options
  • Select an option

  • Save schafeld/775f25d4253dcda3f8bcf59635586c23 to your computer and use it in GitHub Desktop.

Select an option

Save schafeld/775f25d4253dcda3f8bcf59635586c23 to your computer and use it in GitHub Desktop.
Custom Web Components

Custom Web Components

Preview

View in jsPad

Description

Just the two kinds of web components.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>elegant-moon-shiny</title>
</head>
<body>
<my-greeting></my-greeting>
<p id="fancyParagraph" is="my-fancy-paragraph"></p>
</body>
</html>
// Autonomous Custom Element
class MyGreeting extends HTMLElement {
connectedCallback() {
this.innerHTML = '<h1>Bootstrapped elegant-moon-shiny!</h1>';
}
}
customElements.define('my-greeting', MyGreeting);
// Customized Built-in Element
class MyFancyParagraph extends HTMLParagraphElement {
connectedCallback() {
this.textContent = 'This is a fancy paragraph!';
this.style.color = 'blue';
this.classList.add('fancy');
}
}
customElements.define('my-fancy-paragraph', MyFancyParagraph, { extends: 'p' });
/*
const myParaElement = document.getElementById('fancyParagraph');
if (myParaElement) {
myParaElement.classList.add('added-later-style');
}
*/
body {
font-family: 'Verdana', sans-serif;
margin: 0;
padding: 0;
min-height: 100vh;
}
my-greeting {
display: block;
background: white;
padding: 2rem;
border-radius: 1rem;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
}
p.fancy {
background-color: lightyellow;
text-decoration: underline;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment