Overview
ThemiscDomQuery component demonstrates how to query DOM elements within a Lightning Web Component using this.template.querySelectorAll(). This is useful for accessing component state from rendered elements.
Source Component
- miscDomQuery - Queries checkboxes to determine which are selected
Key Features
- Template-scoped queries
- Array manipulation methods
- Filtered element selection
- Property access on queried elements
Implementation
Basic DOM Query
Usethis.template.querySelectorAll() to find elements:
Template
Query Methods
querySelector()
Returns the first matching element:querySelectorAll()
Returns a NodeList of all matching elements:querySelectorAll() returns a NodeList, not an Array. Use Array.from() to convert it to an array and access methods like filter(), map(), and reduce().CSS Selectors
By Tag Name
By Class
By Data Attribute
By Type
Combined Selectors
Common Patterns
Get All Checked Items
Get All Values
Find Specific Element
Validate All Inputs
Shadow DOM Considerations
Lightning Web Components use Shadow DOM, which provides encapsulation:this.templaterefers to the component’s shadow root- Cannot query elements outside the component
- Cannot be queried from parent components
- Provides style and DOM isolation
Unlike Aura components, you cannot use
document.querySelector() to find elements inside a Lightning Web Component. Always use this.template.querySelector() or this.template.querySelectorAll().Accessing Element Properties
Once queried, you can access element properties:Best Practices
- Use data attributes (
data-id) for reliable element selection - Convert NodeList to Array before using array methods
- Check if elements exist before accessing properties
- Avoid querying the DOM unnecessarily; use component state when possible
- Query in event handlers or lifecycle hooks, not during render
- Use
querySelector()when you only need one element - Use
querySelectorAll()when you need multiple elements
Use Data Attributes
Check for Existence
When to Use DOM Queries
DOM queries are useful when:- Accessing component properties (like
checkedorvalue) - Calling methods on child components (like
reportValidity()) - Working with dynamic lists of inputs
- Implementing form validation
- You can track state in component properties
- The data is available through event handlers
- You’re working with @api properties
Source Files
force-app/main/default/lwc/miscDomQuery/
