DOM Querying and Refs
By the end of this lesson, you'll be able to:
- Use this.template.querySelector to access elements within a component's own shadow root
- Use the lwc:ref directive as a more explicit alternative to querySelector
- Recognize when direct DOM access is appropriate versus relying on reactive state
Prerequisites: "Lifecycle Hooks in Depth"
this.template.querySelector
renderedCallback() {
const input = this.template.querySelector('input.primary');
if (input) {
input.focus();
}
}
this.template.querySelector/querySelectorAll search only within the component's own shadow root (Module 1's Shadow DOM lesson) — they cannot reach inside a child component's internal markup, respecting the same encapsulation that keeps components isolated from each other.
The lwc:ref Directive
<input lwc:ref="primaryInput" />
renderedCallback() {
const input = this.refs.primaryInput;
if (input) {
input.focus();
}
}
lwc:ref marks a specific element in the template with a name, then this.refs.<name> retrieves it directly — a more explicit, self-documenting alternative to a CSS selector string, and the currently recommended approach for grabbing a specific known element.
When to Use Direct DOM Access
Both approaches only make sense once the DOM actually exists — typically in renderedCallback, not connectedCallback (which fires before rendering). And they should be used sparingly: most UI state should be driven reactively through properties and conditional rendering (Module 3), not by directly manipulating the DOM — direct access is for genuine escape hatches like managing focus or measuring an element's size.
Exercise
Rewrite this querySelector-based focus call to use lwc:ref instead, naming the ref "searchBox".
Show hint
Add lwc:ref to the template element, then read this.refs.searchBox.
Exercise
Challenge: explain, as a comment, why this.template.querySelector cannot be used to reach into a child component's internal markup.
Show hint
Recall Module 1's Shadow DOM lesson.
DOM Querying and Refs Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A component can only query its own shadow DOM, never reach into a child's internals — and the lwc:ref directive offers a cleaner, more explicit way to grab a specific element than querySelector.