Introduction

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>

Child component

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.querySelectorinstead 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';
    }
}

Parent component

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';**
    }
}

Next recipe

LWC WireGetRecordUser

Feedback?

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>