Shadow DOM: insert content

Insert content from the host element within the Shadow DOM using slots

Generic injection using <slot></slot> inside the HTML5 template

It is possible to define a part of the template into which external HTML content will be “injected”. For this, we use the <slot>…</slot>element, as shown below:

  1. <template id=“mytemplate”>
  2.     <h1 part=‘heading’>This is a shadowed H1</h1>
  3.     <p part=“paragraph”>
  4.         <slot name=“my-text”>My default text</slot>
  5.     </p>
  6. </template>
  7. <body>
  8. <h1 id=“myWidget”>
  9.     <span slot=“my-text”>Injected content using slot elem</span>
  10. </h1>
  11. </body>

Explanations:

  • Look at line 4, this is the “injection point”‘!
  • And line 10 is the content which will be injected into the template code. So, when the classic template instantiation and its addition to a shadow host node in the page is done, the HTML produced will contain “Injected Content” instead of <slot mname=”my-text”></slot>.

See the complete online example at JSBin:

Content injection in HTML templates using slot elements

Useful external resources


Leave a comment