Reproduce slot functionality in Light-DOM component
This code is a simplified example on how to reproduce "slot" functionality when NOT using Shadow DOM in a Web Component. Ordinarily "slots" can only be used when using Shaodw DOM.
HTML
<html>
<body>
<new-comp>
<div slot="mn">this goes into the main slot</div>
<span slot="ftr">this goes into the footer slot</span>
<div slot="mn">this goes into the main slot too</div>
<span slot="hdr">this goes into the header slot</span>
</new-comp>
</body>
</html>
JavaScript
class NewComponent extends HTMLElement {
connectedCallback() {
const html = `
<header>
<slot name="hdr"></slot>
</header>
<main>
<slot name="mn"></slot>
</main>
<footer>
<slot name="ftr"></slot>
</footer>
`;
this.childrenToSlots(html);
}
childrenToSlots(html, src_elems) {
var template = document.createElement('template');
template.innerHTML = html;
const slots = template.content.querySelectorAll("slot");
for (const slot of slots) {
const slotChildren = this.querySelectorAll(`[slot='${slot.name}']`);
slot.replaceWith(...slotChildren);
}
this.replaceChildren(template.content);
}
}
customElements.define("new-comp", NewComponent);