I am trying to retrieve template content, insert it into a custom element with shadow DOM, and style the span
elements inside the template
using the ::slotted
selector. However, it seems like this functionality is not working as I expected.
<!doctype html>
<html lang="en">
<head>
<template id="template">
<span>element from template</span>
</template>
</head>
<body>
<script type="text/javascript">
class WithShadowDom extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `
<style>
::slotted(span) {
font-size: 25px;
}
</style>
`;
shadowRoot
.appendChild(document.createElement('slot'))
.appendChild(
document.getElementById('template').content.cloneNode(true)
);
}
}
window.customElements.define('with-shadow-dom', WithShadowDom);
const myCustomElement = document.createElement('with-shadow-dom');
document.body.appendChild(myCustomElement);
</script>
</body>
</html>
The issue arises when trying to apply the font-size
CSS property in the code snippet below:
shadowRoot
.appendChild(document.createElement('slot'))
.appendChild(document.getElementById('template').content.cloneNode(true));
However, when adding a child span
directly inside the custom element, the font-size
styles are successfully applied:
const span = document.createElement('span');
span.innerHTML = 'asdffad';
shadowRoot
.appendChild(document.createElement('slot'))
.appendChild(span);