Treesa
Treesa

Reputation: 383

Web Components: how to access a slotted element using shadowRoot.querySelector

Hi I am new to Web Components concept. I wanted to know if we can access a slotted element using shadowRoot.querySelector

I have implemented an input field as slot for setting some values dynamically. And have a class added to it 'column-title'. I am trying to access this element in connectedCallback() like this

var titleInput = this.shadowRoot.querySelector('.column-title')

But it returns null.

Please help.

Upvotes: 7

Views: 15307

Answers (2)

Amber-Williams
Amber-Williams

Reputation: 101

Going off of @royyko 's response. The better answer here is instead of giving a class or id with the purpose to grab the slot... use the already provided identifier, its name. To do this you would do the following this.shadowRoot.querySelector('slot[name=interior]')

Upvotes: 7

rovyko
rovyko

Reputation: 4577

I'm not sure what the issue is, but you should be able to get a slot using querySelector and its class. I've mocked up an example below.

The console will print out references to the slot. If you're attaching a class just for the purpose of finding the slot then it's probably better to set an id (assuming that it's within a shadow root) and find it with this.shadowRoot.getElementById('my-slot-id')

customElements.define('blue-box',
  class extends HTMLElement {
    constructor() {
      super();
      var template = document
        .getElementById('blue-box')
        .content;
      const shadowRoot = this.attachShadow({
          mode: 'open'
        })
        .appendChild(template.cloneNode(true));
    }
    
    connectedCallback() {
    	console.log(this.shadowRoot.querySelector('slot.target-slot'));
    }
  });
<template id="blue-box">
  <style>
  .blue-border {
    border: 2px solid blue;
    padding: 5px;
    margin: 5px;
  }
  </style>
  <div class='blue-border'>
    <slot name='interior' class='target-slot'>NEED INTERIOR</slot>
  </div>
</template>

<blue-box>
  <span slot='interior'>My interior text</span>
</blue-box>
<blue-box>
  <span slot='interior'>
  Check Here: <input type='checkbox'>
  </span>
</blue-box>

Upvotes: 5

Related Questions