Search code examples
typescriptlit-element

How do you access a lit-element render root after overriding createRenderRoot?


I've been playing around with lit-element, and I want to grab my custom element to run a getElementById. The only examples I can find use the shadow root (since that's the recommended way to use lit-element). How do you get access to your custom element to run a query on just your element?

import { LitElement, html } 
from 'https://unpkg.com/lit-element/lit-element.js?module';

class RenderRootTest extends LitElement {
  constructor() {
    super();
  }
  render () {
    const renderRoot = this.shadowRoot; //Won't work, because I'm overriding the shadowroot
    return html`
      <div>Rendered</div>
      ${renderRoot ? 
        html`<div>Render root found</div>` :
        html``
      }
    `;
  }
  createRenderRoot() {
    return this;
  }
}

customElements.define('render-root-test', RenderRootTest);

Solution

  • I found the answer myself after enough tinkering. You can either use this.renderRoot or just this. However, note that certain methods such as .getElementById don't seem to exist. If anyone has any additional details on this topic, I would appreciate it.

    ex.

    import { LitElement, html } 
    from 'https://unpkg.com/lit-element/lit-element.js?module';
    
    class RenderRootTest extends LitElement {
      constructor() {
        super();
      }
      render () {
        const renderRoot = this.renderRoot;
        return html`
          <div>Rendered</div>
          ${renderRoot ? 
            html`<div>Render root found</div>` :
            html``
          }
        `;
      }
      createRenderRoot() {
        return this;
      }
    }
    
    customElements.define('render-root-test', RenderRootTest);