I want to get template content, inject it into a custom element with shadow DOM and apply styles to span
inside template
via ::slotted
selector but this doesn't seem to work as 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 below piece doesn't work as expected. The font-size
css doesn't get applied.
shadowRoot
.appendChild(document.createElement('slot'))
.appendChild(document.getElementById('template').content.cloneNode(true));
While when directly appending a child span
inside custom element the font-size
gets applied.
const span = document.createElement('span');
span.innerHTML = 'asdffad';
shadowRoot
.appendChild(document.createElement('slot'))
.appendChild(span);