Search code examples
focusweb-componentshadow-domlit

How to manually set focus on element in a shadow DOM (Lit Web Component)


I'm building a select/dropdown component as a Lit web component. To have consistent styling, this is NOT using a native select. I'm using divs and adding logic to have them appear when and where appropriate. I also want this component to be fully accessibility, including having keyboard control support.

I'm at the part where after a div is clicked(or space/enter is used on the keyboard), and the dropdown div appears. Now I need to have the focus changed from the clicked div (that triggers the dropdown), to the first item in the dropdown.

However, I cannot figure out how to manually focus on that element. I know that the document can't detect element's in the shadow DOM, and I'm assuming I need to use renderRoot (https://lit.dev/docs/components/shadow-dom/), but I can't find functions or methods to cause the element to become focused. I can use this.renderRoot.querySelector('#first-dropdown-item') to get the needed element, but then I don't know how to focus on it.

I can't find that in the documentation either.

I also need to trap the focus in this div until the dropdown is closed. I'm not sure how to do that either.


Solution

  • I ended up using ShadowRoot to achieve this. Example:

    this.shadowRoot.getElementById('{{id}}')?.focus()
    

    You can also use querySelector() if their is no id on the element; Ex:

    this.shadowRoot.querySelector('{{selector}}')?.focus()