Skip to content

Instantly share code, notes, and snippets.

@yossan
Last active Oct 13, 2020
Embed
What would you like to do?
web components by using templates
<html>
<head></head>
<body>
<template id="my-paragraph">
<style>
p {
color: white;
background-color: #666;
padding: 5px;
}
</style>
<p>My paragraph</p>
</template>
<script>
class MyParagraph extends HTMLElement {
constructor() {
super()
let template = document.getElementById('my-paragraph')
let templateContent = template.content
const shadowRoot = this.attachShadow({mode: 'open'})
.appendChild(templateContent.cloneNode(true))
}
}
customElements.define('my-paragraph', MyParagraph)
</script>
<my-paragraph></my-paragraph>
</body>
</html>
<html>
<head></head>
<body>
<template id="my-paragraph">
<style>
p {
color: white;
background-color: #666;
padding: 5px;
}
</style>
<p>My paragraph</p>
<p><slot name="my-text">My default text</slot></p>
</template>
<script>
class MyParagraph extends HTMLElement {
constructor() {
super()
let template = document.getElementById('my-paragraph')
let templateContent = template.content
const shadowRoot = this.attachShadow({mode: 'open'})
.appendChild(templateContent.cloneNode(true))
}
}
customElements.define('my-paragraph', MyParagraph)
</script>
<p>This is standard p element.</p>
<my-paragraph>
<span slot="my-text">Let's have some different text!</span>
</my-paragraph>
<my-paragraph>
<ul slot="my-text">
<li>Let's have some different text!</li>
<li>In a list!</li>
</ul>
</my-paragraph>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment