shadow DOM slots

Shadow DOM supports <slot> elements, that are filled by the content from light DOM.

browser โŸฉ web components โŸฉ implement โŸฉ shadow DOM โŸฉ slots

if shadow DOM defines more than one and names those slots with a name attribute, then children of the shadow host can specify which slot they would like to appear in by specifying a slot="slotname" attribute.

Fallback Content

  • if we put something inside <slot>(in shadow DOM), it becomes the fallback content, browser shows it if thereโ€™s no corresponding element in light DOM. ๐Ÿ‘‰ See tab 2๏ธโƒฃ below.

Default Slot

  • The first unnamed <slot> in shadow DOM is a โ€œdefault slot". It gets all nodes from the light DOM that arenโ€™t slotted elsewhere. ๐Ÿ‘‰ See tab 1๏ธโƒฃ below.

Code Example

<user-card>
  <!-- โญ๏ธ light DOM: slotted elements -->
  <!-- โญ๏ธ only top-level children may have [slot="โ€ฆ"] attributeโ—๏ธ -->
  <span slot="username">John Smith</span>
  <span slot="birthday">2001.01.01</span>
</user-card>

Named Slots

  • for each<slot name="X"> in shadow DOM, the browser looks for[slot="X"] in the light DOM and insert it into the slot, the result is called flattened DOM. ๐Ÿ‘‰ See code in "shadow DOM", "flattened DOM" tabs above.

  • if there are multiple elements in light DOM with the same[slot="X"], they are appended into the same<slot name="X"> (in shadow DOM), one after another.

Flattened DOM

Last updated

Was this helpful?