The main concept included in this recipe is enabling the Light DOM and then how elements are accessed from the parent.
<aside> ๐ก If you are not familiar with the Light DOM and its differences with the Shadow DOM, review this section before digging into this LWC Shadow DOM & Light DOM
</aside>
<aside>
๐ Find the parent component in this folder: force-app/main/default/lwc/lightDomQuery
and the child component in this one: force-app/main/default/lwc/lightDomQueryChild
</aside>
Activating the Light DOM involves 1 line of code in the template and 1 line in the Javascript.
**<template lwc:render-mode="light"> // Render Mode set to Light**
<div class="slds-var-p-around_small">
<p class="lightDomParagraph">Click any button to change this text</p>
<div class="slds-var-m-top_small">
<lightning-button
onclick={handleButtonClick}
label="Change Text"
></lightning-button>
</div>
</div>
</template>
In this Javascript file, selecting the elements is using this.querySelector
instead of this.template.querySelector
:
import { LightningElement } from 'lwc';
export default class LightDomQueryChild extends LightningElement {
**static renderMode = 'light'; // <-- Render Mode set to Light**
handleButtonClick() {
// Within Light DOM components, use this.querySelector
// instead of this.template.querySelector to access elements
this.querySelector('p.lightDomParagraph').innerText =
'Text changed by child';
}
}
The parent component template includes the child component as usual:
...
<div class="slds-var-m-around_medium">
<c-light-dom-query-child
class="slds-show slds-is-relative"
></c-light-dom-query-child>
</div>
...
The real difference when using the Light DOM appears on the Javascript file. The parent can access elements in the child component just by using this.template.querySelector
:
import { LightningElement } from 'lwc';
export default class LightDomQuery extends LightningElement {
handleButtonClick() {
// Elements that are inside a Light DOM child component
// are directly accessible by the parent
**this.template.querySelector('p.lightDomParagraph').innerText =
'Text changed by parent';**
}
}
Did you find an issue/mistake? You donโt like something? Do you have external content that I should link to improve the learning process? Did you find it helpful? Any of those are super valuable to me. So, please write me at [email protected], and promise to answer.
<aside> โ๏ธ Jump to the main page: The LWC Recipes Cookbook
</aside>