Access lit-element render root after override: createRenderRoot()

How can I access my custom element render-root-test to run a query such as getElementById?

Using the LitElement library, it’s recommended to use the shadowRoot to access custom elements. However, I’m overriding the shadowRoot by using the createRenderRoot() method, so this won’t work. How do I access my custom element render-root-test to run a query such as getElementById?

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);

Since you’re using createRenderRoot() to override the shadowRoot, you can access your custom element render-root-test using this instead of this.shadowRoot. Here’s an updated version of your render() method with this change:

render () {
  const renderRoot = this; // Access the custom element using this instead of this.shadowRoot
  return html`
    <div>Rendered</div>
    ${renderRoot.querySelector('#my-element-id') ? // Use querySelector to find an element by ID
      html`<div>Render root found</div>` :
      html``
    }
  `;
}

Assuming you have an element with the id of my-element-id, this code will check if it exists within your custom element’s createRenderRoot().