How do developers use template.querySelector to access elements inside a component's Shadow DOM?
Answer
Basics: Each LWC renders into a shadow root (this.template). Elements in it are encapsulated, so document.querySelector cannot find them. this.template.querySelector('.cls') returns the first match in this component's template (or null), and querySelectorAll returns a static NodeList. Use it to call methods on child components (for example lightning-input's reportValidity()), focus an element, or read values.
How it works: Query only after the DOM exists: in event handlers or renderedCallback, never in the constructor or connectedCallback. Select with class names, tag names or data-* attributes. Do not select by id: the engine rewrites ids to keep them unique per instance, so #myId selectors are unreliable (use data-id instead). Slotted content from a parent belongs to the parent's template, so you reach it with this.querySelector (not this.template). For a public method on a child, query the child and call it, e.g. this.template.querySelector('c-child').refresh().
Advanced / deep dive: Newer releases add lwc:ref="name" in markup and this.refs.name in JS, which is faster and clearer than selectors for elements you own; it resolves only to elements in your own template. Shadow DOM encapsulation is enforced by synthetic shadow (or native shadow in LWS-era contexts), so you cannot style or select inside a child's template. For elements you inject yourself (third-party charts, innerHTML), add lwc:dom="manual" to the container; otherwise injected nodes are not allowed. Light DOM components () are the exception: there you use because there is no shadow root. Prefer declarative bindings and events over DOM traversal; querying is for focus, validation and library integration.