Development questions

What is Shadow DOM in LWC and how do you query elements inside a component?

DevelopmentMedium

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-id attributes or lwc:ref rather than id (ids get rewritten to be unique).
  • Elements passed via slots are in the light DOM; query them with this.querySelector().
  • document.querySelector will not reach inside a component.

Styling is scoped; use styling hooks (CSS custom properties) to customize base components.

lwcshadow-domdom