0

I have a component which uses named slots from <another-component>. I was trying to get the <span> by calling this.shadowRoot.getElementById('title') in <another-component>, it always returns null:

  render() {
    return html`
      <another-component>
        <h2 slot="header">
          <span id="title"></span>
        </h2>
        <div slot="footer">
          ${this.renderFooter()}
        </div>
      </another-component>
    `;
  }

Any ideas?

Hammerhead
  • 1,044
  • 8
  • 19
  • 1
    Does this answer your question? [Shadow Root getElementsByClassName](https://stackoverflow.com/questions/53460850/shadow-root-getelementsbyclassname) – Supersharp Dec 12 '19 at 19:00

1 Answers1

0

After some digging, i found this is by design. Please correct me if i'm wrong. Basically, you can only access a DOM element under a shadow root where it's defined no matter if it's in a <slot> or not.

For example, let's say in your main component, you have a component A with an element with an ID:

// main component's render
<a>
  <p id="title"></p>
</a>

Component A uses component B, and maps its slot content to another slot in component B:

// component A's render
<b>
  <p slot="header">blabla</p>
  <slot slot="content"></slot>
</b>

Neither A nor B can access the element via shadowRoot.getElementById. Only the main component can get the element by ID.

Hammerhead
  • 1,044
  • 8
  • 19