Search code examples
web-componentshadow-domhtml5-templatenative-web-component

Web component and shadow root


I create a web component with this code where I use template:

let tmpl = document.createElement('template');
tmpl.innerHTML =`<style>
div {
   color: green;
   display: inline;
   margin: 3px;
}

p {
   border: 1px solid black;
}
</style>

<p>
Hello my name is:
<div>Web</div>
<div>Component</div>
</p>`;
this.shadowRoot.appendChild(tmpl.content.cloneNode(true));

But in shadow root from console I see this content which not the same:

enter image description here


Solution

  • It has nothing to do with Shadow DOM or Custom Element.

    Actually the same behaviour happens with normal DOM : you cannot insert a <div> element inside a <p> element. The latter only accepts phrasing content.

    See SO question: Why <p> tag can't contain <div> tag inside it?