Accessing Elements in the Component in LWC
1 2 3 4 5 6 7 8 9 10 11 12 |
<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> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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>' } } |
Template Looping in LWC Dynamic CSS in LWC