Web component: How to query children of a slot
Asked Answered
W

3

7

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?

Weywadt answered 12/4, 2022 at 15:30 Comment(0)
A
8

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"]').

Atelectasis answered 13/4, 2022 at 5:57 Comment(0)
W
0

Figured it out:

this.querySelectorAll('[slot="content"]')
Weywadt answered 12/4, 2022 at 16:10 Comment(0)
I
0

To get a NodeList of the elements assigned to a specific slot within a web component, you can use the assignedElements method, which is part of the Shadow DOM API. If you are using the Lit library, you can simplify this process by using the @queryAssignedElements decorator from lit/decorators.js.

import { LitElement, html } from 'lit';
import { queryAssignedElements } from 'lit/decorators.js';

class MyComponent extends LitElement {
  @queryAssignedElements({ slot: 'content' })
  private content?: Array<HTMLElement>;

  ...
}

customElements.define('my-component', MyComponent);

It simplifies the process of accessing assigned slot elements, reducing boilerplate code and, The property will automatically update when the slot content changes.

Issacissachar answered 15/5 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.