I'm trying to make a custom element with a shadow, but when I add a shadow, the content of the element doesn't render. Here's my code:
JavaScript:
class CustomElement extends HTMLElement {
constructor (){
super();
var shadow = this.attachShadow({mode: 'open'});
var content = document.createElement("DIV");
content.innerText = "hello world";
shadow.appendChild(content);
}
}
customElements.define("custom-element", CustomElement);
HTML:
<custom-element>blah blah blah</custom-element>
But all it renders is the text "hello world"
It's the normal behaviour of a Shadow DOM : the Shadow DOM content masks the original content (called the Light DOM).
If you want to reveal the Light DOM content, use <slot>
in the Shadow DOM.
class CustomElement extends HTMLElement { constructor (){ super(); var shadow = this.attachShadow({mode: 'open'}); var content = document.createElement("DIV"); content.innerHTML = "hello world: <br> <slot></slot>"; shadow.appendChild(content); } } customElements.define("custom-element", CustomElement);
<custom-element>blah blah blah</custom-element>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.