Register an Event Handler on a Shadow DOM Element Using Code with Lit Components

TL;DR

public override firstUpdated() {
    this.shadowRoot
        ?.querySelector('.classes-I-want')
        ?.addEventListener('click', () => console.log('Handling click event.'));
}

The challenge I had with registering the event handler was finding the right time in the lit.dev lifecycle to catch the DOM element. On top of that, I had to find the element in the Shadow DOM.

Well lit.dev provides easier ways of accomplishing what I want to do. The problem here is that my component imports html templates from an external file that get conditionally rendered. So if I had my own template inside the component file I’m using, I would have chosen the @click attribute to assign my event handler. I could also pass the handler to each template through a function and render it, but that would create redundancy.

So in the end, after trying createRenderRoot() and connectedCallback(), I discovered that the shadowRoot property of the component could find my HTMLElement in the rendered template, and I could also capture slotted children components inside of that handler as well.

Leave a Reply

Your email address will not be published. Required fields are marked *