Accessing Slotted Elements with slot.assignedNodes()
What you'll learn: How to programmatically retrieve the actual Light DOM elements that have been distributed into a slot within your Web Component.
The Core Idea
When you create slots in Shadow DOM, you're setting up placeholders for content. But what if your component needs to know what content actually landed in those slots? That's where assignedNodes() and assignedElements() come in.
These methods let you query a <slot> element to discover what Light DOM nodes the browser assigned to it. Think of it like checking who actually showed up to a party you're hosting—the slot is the invitation, but assignedNodes() tells you who walked through the door.
assignedNodes() vs assignedElements()
assignedNodes()returns all nodes assigned to the slot, including text nodes and commentsassignedElements()returns only Element nodes (filters out text/comments)
Both accept an optional { flatten: true } parameter to include fallback content when no Light DOM content is slotted.
Example Usage
class InfoCard extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<slot name="title"></slot>
<slot name="content"></slot>
`;
const titleSlot = this.shadowRoot.querySelector('slot[name="title"]');
const assignedElements = titleSlot.assignedElements();
console.log('Title slot contains:', assignedElements);
// You can now manipulate or inspect these elements
}
}
This is particularly useful when you need to validate slotted content, apply additional processing, or coordinate between your component's logic and the projected Light DOM.
Key Takeaway: Use assignedNodes() or assignedElements() on a <slot> element to programmatically access the Light DOM content that users projected into that slot—essential for components that need to inspect or react to their distributed content.