I have a lightning-button-icon with dynamic name and i want to update its selected attribute based on the name. Can someone tell me how can i do that?
my code (UPDATED):
<lightning-layout-item size="3">
<lightning-button-icon-stateful
data-class="slelectState"
data-index1={inx1}
data-index2={inx2}
data-id={pair.key}
name={pair.key}
icon-name="utility:check"
selected={selectState}
alternative-text="True"
onclick={handleSelect}>
</lightning-button-icon-stateful>
<lightning-button-icon-stateful
data-class="UnslelectState"
data-index1={inx1}
data-index2={inx2}
data-id={pair.key}
name={pair.key}
icon-name="utility:close"
selected={unSelectState}
alternative-text="False"
onclick={handleUnSelect}>
</lightning-button-icon-stateful>
</lightning-layout-item>
I tried this code this.template.querySelector(
[name="${selectedname}"])
as per @sfdcfox answer here but it gave me null value.
Best Answer
As of now, You can only query elements with the attributes that are exposed on the element - in this case
lightning-button-icon-stateful
. The attributename
is not directly placed on this element but it is on internal element.If you want to see what items you can query, look at the following example.
For example
When you do
console.log(this.template.querySelector('lightning-button-icon-stateful'));
Output in console:
So we can only do querySelector with attributes data-* (data-index1, data-index2) and c-app_app (auto generated based on class).
It cannot retrieve elements with other attributes using querySelector, so the following will always be null.
So in short, you can only retrieve data attributes in the given example as other elements are actually placed on internal element.
Reference: How to target LWC by name attribute?
Alternatively, you can query based on DOM element and iterate the result and verify the name. something like this.