Skip to content

Instantly share code, notes, and snippets.

@yossan
Last active October 13, 2020 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yossan/0718e8e1690caaff29964d74fe35ad56 to your computer and use it in GitHub Desktop.
Save yossan/0718e8e1690caaff29964d74fe35ad56 to your computer and use it in GitHub Desktop.
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