Blog>
Snippets

Accessing Named Slot Content from JavaScript

Describes methods for accessing and manipulating content passed to named slots from within the child component's JavaScript.
<!-- HTML -->
<custom-element>
  <div slot='named-slot'>Content for the named slot</div>
</custom-element>
An HTML structure where a 'custom-element' uses a named slot 'named-slot' to distribute content.
/* CSS */
custom-element::slotted([slot='named-slot']) {
  color: blue;
}
CSS targeting slotted content within the 'named-slot'. It changes the text color to blue.
// JavaScript

class CustomElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `
      <slot name='named-slot'></slot>
    `;
  }

  connectedCallback() {
    const slot = this.shadowRoot.querySelector('slot[name="named-slot"]');

    slot.addEventListener('slotchange', (e) => {
      const nodes = slot.assignedNodes();
      console.log('Slot content changed:', nodes);
      // Additional manipulation of nodes can be done here
    });
  }
}

window.customElements.define('custom-element', CustomElement);
JavaScript defining a custom element with a named slot. It adds a listener for the 'slotchange' event that logs the content of the named slot whenever it changes.