What is Shadow DOM in LWC and how do you query elements inside a component?
Answer
Shadow DOM encapsulates a component's markup and CSS so outside code and styles can't accidentally affect it. Salesforce uses synthetic shadow (a polyfill) in most contexts.
Querying:
- Use
this.template.querySelector()/querySelectorAll()for elements in your own template. - Use
data-idattributes orlwc:refrather thanid(ids get rewritten to be unique). - Elements passed via slots are in the light DOM; query them with
this.querySelector(). document.querySelectorwill not reach inside a component.
Styling is scoped; use styling hooks (CSS custom properties) to customize base components.
lwcshadow-domdom