Search code examples
javascriptecmascript-6ecmascript-5

How to get element inside slot in JS


I have a question regarding slots

example:

In page1.js

<div slot="slotName1">
  <div class="header">
    <div class="content">
      content
    </div>
  </div>
</div>
<div slot="slotName2">
  <div class="header">
    <div class="content">
      content
    </div>
  </div>
</div>

in page2.js

<div>
<slot name="slotName1"></slot>
<slot name="slotName2"></slot>
</div>

how to access content class element in page2.js, I am sure that slot is available then I tried below it is not working for me

const expanderT = this.shadowRoot.querySelector('slot[name="slotName1"]');
console.log('ex: ', expanderT.querySelector('content'));

Solution

  • Slotted elements are not really moved in the DOM, they just get rendered at their corresponding slots by the browser. In other words, slotted elements still obey the DOM's hierarchical structure, meaning you can't access them using querySelector() from the shadow root because querySelector() traverses the document's markup.

    What you want is the assignedElements() method on the HTMLSlotElement interface which retrieves the list of DOM elements assigned to an instance of a slot element.

    In your case, you will want something like:

    const expanderT = this.shadowRoot.querySelector('slot[name="slotName1"]');
    console.log('ex: ', expanderT.assignedElements()[0].querySelector('.content'));
    

    You were also missing the dot before "content" to indicate that you are selecting an element with the class "content". Without the dot, it attempts to match a tag name.