Assigning Content to Slots with slot Attribute
You'll learn how to explicitly direct Light DOM elements into specific named slots in your Web Component's Shadow DOM.
Understanding the Slot Attribute
You've seen how Shadow DOM can define named slots for content projection. Now comes the key mechanism: the slot attribute on Light DOM elements tells the browser which named slot an element should fill.
Think of it like sorting mail into labeled mailboxes. Your Shadow DOM creates mailboxes (slots) with names like "header" or "footer". The slot attribute on your Light DOM elements acts as the mailing label that says "deliver this to the 'header' box."
How It Works
When you use a custom element in your HTML, you add the slot attribute to children elements to target specific named slots:
<my-card>
<h2 slot="header">Welcome</h2>
<p>This goes to the default slot</p>
<button slot="footer">Click Me</button>
</my-card>
Inside your Shadow DOM template:
<template id="card-template">
<div class="card">
<slot name="header"></slot>
<slot></slot> <!-- default slot catches <p> -->
<slot name="footer"></slot>
</div>
</template>
The <h2 slot="header"> gets projected into <slot name="header">, the button goes to the footer slot, and the paragraph (with no slot attribute) falls into the unnamed default slot.
Key Takeaway: The slot attribute on Light DOM elements acts as a routing mechanism, explicitly assigning content to named slots in the Shadow DOM—without it, elements go to the default unnamed slot.