Search code examples
javascriptweb-componentnative-web-component

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.


Solution

  • 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>