querySelector searches an element’s descendants with a CSS selector and returns the first match. Calling it on document searches the page; calling it on a component scopes the search to that component. section 2.4
Inside a Web Component, use this.querySelector() when the target belongs to the component’s own markup. A selector such as '.image-container' or 'button.forward' reaches the generated child without searching unrelated page content. section 2.6 section 2.4
Use querySelector to:
- Find a child element and immediately change its style, such as applying a background image or positioning a slider thumb. section 2.6 section 2.4
- Find controls and attach event listeners, keeping button and menu handling inside the component scope. section 2.6 section 6.5
- Cache repeated lookups when update logic queries the same elements frequently or when selectors make controller code harder to read. section 6.5
Scoped lookup in a photo carousel
showPhoto() { this.querySelector('.image-container').style.backgroundImage = 'url(' + this._photos[this._photoIndex] + ')'; } The method finds the carousel’s image container, rather than an element with that class elsewhere on the page. The same pattern locates its back and forward buttons before registering click listeners. section 2.6
Caching a DOM map
mapDOM(scope) { return { logoPicker: scope.querySelector('.logo-picker select'), backgroundPicker: scope.querySelector('.background-picker select'), logo: scope.querySelector('.logo'), background: scope.querySelector('.biz-card') }; } The component can then use this.dom.logo or this.dom.background instead of repeating selectors during every update. section 6.5
Listing 2.10. Adding a showPhoto method
connectedCallback() {
this._photoIndex = 0;
this._photos = this.getAttribute('photos').split(',');
this.innerHTML = '<h2>'+ this.getAttribute('title') + '</h2>' +
'<h4>by '+ this.getAttribute('author') + '</h4>' +
'<div class="image-container"></div>' +
'<button class="back"><</button>' +
'<button class="forward">></button>';
this.showPhoto(); #1
}
showPhoto() { #2
this.querySelector('.image-container').style.backgroundImage =
'url(' + this._photos[this._photoIndex] + ')';
}
Shows querySelector used within a complete component method to locate a descendant and update it. section 2.6
