Another Salesforce blog!!!

Salesforce, Apex

Accessing Elements in the Component in LWC

<template>
    <lightning-card title="querySelector">
        <div class="slds-var-m-around_medium">
            <h1>Header!!!</h1>
            <template for:each={userNames} for:item="user">
                <div class="name" key={user}>{user}</div>
            </template>
            <div class="child" lwc:dom="manual"></div>
             <button onclick={fetchDetailHandler}>Fetch details</button>
        </div>
    </lightning-card>
</template>
import { LightningElement } from 'lwc';

export default class HelloQuerySelectorDemo extends LightningElement {
    userNames =["One", "Two", "Three", "Four"]
    fetchDetailHandler(){
        const elem = this.template.querySelector('h1')
        elem.style.border="1px solid red";
        console.log(elem.innerText)

        const userElements = this.template.querySelectorAll('.name')
        Array.from(userElements).forEach(item=>{
            console.log(item.innerText)
            item.setAttribute("title", item.innerText)
        })

        ///  lwc:dom="manual" demo
        const childElem = this.template.querySelector('.child')
        childElem.innerHTML = '<p>Hey i am a child element</p>'
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *