move lightDOM to shadowDOM
by Danny Engelman
HTML
<script>
customElements.define('my-element', class extends HTMLElement {
constructor() {
super()
//create shadowDOM (thus creating lightDOM) and append Template
this.attachShadow({
mode: 'open'
})
.append(document.getElementById(this.nodeName).content.cloneNode(true))
}
connectedCallback() {
//see the console!!
let savedHTML = this.outerHTML;
//append content from lightDOM
const append = (selector) =>
this.shadowRoot.append(...this.querySelectorAll(selector), savedHTML);
if (this.outerHTML.includes("timeout"))
setTimeout(() => append('DIV'))
else
append('DIV');
}
})
</script>
<template id="MY-ELEMENT">
<style>
:host {}
h4 {
background: yellow;
}
div {
background: lightcoral;
height: auto;
}
</style>
<h4>
<slot name="title"></slot>
</h4>
</template>
<my-element>
<!-- begin lightDOM because my-element has shadowDOM -->
<span slot="title">whole SPAN is slotted</span>
<div>I am appended</div>
<div>appended too</div>
<p>I remain (invisible) in lightDOM</p>
<!-- end lightDOM -->
</my-element>
<my-element timeout>
<!-- begin lightDOM because my-element has shadowDOM -->
<span slot="title">slotted too</span>
<div>appended again</div>
I remain (invisible) in lightDOM
<!-- end lightDOM -->
</my-element>