TL;DR: When one custom element is inside of another, the second fails to render. Why is this and how is it fixed?
Explanation
I created three custom HTML elements and two template
s using JS (seen below).
const baseTemplate = document.createElement("template");
baseTemplate.innerHTML = `
<slot name="left-pane">Warning: left-pane not included</slot>
<slot name="right-pane">Warning: right-pane not included</slot>
`;
const paneTemplate = document.createElement("template");
paneTemplate.innerHTML = `<slot name="content">Warning: no content included</slot>`;
class PageBase extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: "closed" });
let clone = baseTemplate.content.cloneNode(true);
shadow.append(clone);
}
}
class LeftPane extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: "closed" });
let clone = paneTemplate.cloneNode(true);
shadow.append(clone);
}
}
class RightPane extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: "closed" });
let clone = paneTemplate.cloneNode(true);
shadow.append(clone);
}
}
customElements.define("page-base", PageBase);
customElements.define("left-pane", LeftPane);
customElements.define("right-pane", RightPane);
In the HTML document (seen below), when right-pane
or left-pane
is put inside another custom element (in this case page-base
), it is not rendered in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
[...]
<script src="js/layout.js" type="module"></script> <!---This is the JS file seen above--->
</head>
<body>
<page-base>
<div slot="left-pane">
<p>Thing 1</p>
</div>
<div slot="right-pane">
<right-pane>
<p slot="content">Thing 3</p>
</right-pane>
<p>Thing 2</p>
</div>
</page-base>
</body>
</html>
Question: Thing 1
and Thing 2
are rendered, but not Thing 3
. Why is this and how do I fix it?
I’ve tried using each custom element on their own, and they work fine putting header or paragraph tags inside, but not for the custom elements.