I'm using the following in Javascript functions in LWC "var uiSection = this.template.querySelector('[data-id="sidebar"]');" to find a UI element with data-id=sidebar. This works ok when exists within the same in the LWC. However if I call "var uiSection = this.template.querySelector('[data-id="sidebar"]');" from an onclick in a child it can't find it. The following is a pseudocode of my code
Markup
<div class="expander active" data-id="expander-control" onclick={divClickHandler} ></div>
<ul class="sidebar" data-id="sidebar">
<template for:each={stations} for:item="station">
<li class="active stationItem" key={station}>
<div class="item-header">
<div class="label">{station.Name}</div >
</div>
<template if:true={station.Station_Assets__r}>
<div class="item-content">
<template for:each={station.Station_Assets__r} for:item="asset">
<ul class="typelist" style="max-height: 156px;" key={asset.Id} onclick={assetClickHandler}>
<li>
<span key={asset.Id} id={asset.Id} data-id={asset.Id} class="assetType" data-classname="assetType" onclick={assetClickHandler}>{asset.Name}</span>
</li>
</ul>
</template>
</div>
</template>
</li>
</template>
</ul>
</div>
JS Functions
divClickHandler(event, component) {
var uiSection = this.template.querySelector('[data-id="sidebar"]');
if(uiSection){
console.log('Found section');
}else{
console.log('Not Found');
}
}
assetClickHandler(event, component) {
var uiSection = this.template.querySelector('[data-id="sidebar"]');
if(uiSection){
console.log('Found section from asset');
}else{
console.log('Not Found from asset');
}
}
...
My call to divClickHandler finds the UI with the data-id ok. My call to assetClickHandler does not find it. Should this.template.querySelector not work across the whole DOM or does it only work in the immediate template? To access the same UI element in a child what would be the best way to do this? Any tips would be appreciated.