Say I have a native web component, and it has a slot:
<slot id="CONTENT_SLOT" name="content"></slot>
const CONTENT_SLOT = this.shadowRoot.getElementById("CONTENT_SLOT")
finds the element, but CONTENT_SLOT.children
is empty.
this.shadowRoot.querySelectorAll('[slot="content"]')
returns an empty node list too.
document.querySelectorAll('[slot="content"]')
finds items in the slot, but for all web components.
How can I get a NodeList of the elements in the content
slot for the current web component instance only?
You can get the elements that are assigned to the slot with assignedElements()
.
this.shadowRoot.querySelector('#CONTENT_SLOT').assignedElements();
The difference between doing this and this.querySelectorAll('[slot="content"]')
is that you get the elements that are actually in the slot instead the elements who have the slot
attribute. Elements that aren't a direct child of the custom-element and do have the attribute will not be in the <slot>
, but they will be found with this.querySelectorAll('[slot="content"]')
.