3

I want to use a dynamic value inside querySelectorAll method but unable to use it.

let Product= event.target.dataset.item;
alert(Product);
let checkboxes = this.template.querySelectorAll('[data-id="${Product}"]');

The above mentioned code is not working because it is not able to comprehend the value of product inside. **The alert is providing the correct value so the variable has correct data.

On hardcoding the value of the product its working fine

let Product= event.target.dataset.item;
 alert(Product);
 let checkboxes = this.template.querySelectorAll('[data-id="OpenEdge"]');

added HTML:

<div class="slds-col slds-size_1-of-5 slds-align_absolute-center">
                        <span>
                            <lightning-input class="slds-p-left_xx-large" type="checkbox" label="" data-item={product.MasterLabel} onchange={handleChange}>
                            </lightning-input>
                        </span>
                    </div>

                    <div class="slds-col slds-size_1-of-5 slds-align_absolute-center">
                    <template if:true={product.Product_Alerts__c}>
                        <span>
                            <lightning-input class="slds-p-left_xx-large" type="checkbox" data-id="{product.MasterLabel}"></lightning-input>
                            <lightning-input class="slds-p-left_xx-large" type="checkbox" data-id={product.MasterLabel}  ></lightning-input>
                        </span>
                    </template>
                    </div>

Is there any other way of using variable inside the method?

9
  • can you add markup as well? Dec 13, 2019 at 9:32
  • didnot get what you meant to say exactly Dec 13, 2019 at 9:32
  • Can you add html file as well, minimum viable code to reproduce, or if you can provide playground link it would be even better Dec 13, 2019 at 9:33
  • Hi,I have added HTML snippet in the question itself.Please check Dec 13, 2019 at 9:38
  • Try with this:- let checkboxes = this.template.querySelectorAll('[data-id="'+Product+'"]'); Dec 13, 2019 at 9:45

2 Answers 2

3

To query the elements dynamically in Lightning Web Component, You need to change your markup as below:-

let Product= event.target.dataset.item;
alert(Product);
let checkboxes = this.template.querySelectorAll('[data-id="'+Product+'"]');

It was the syntax that was wrong in your case.

3

Just as an alternative if the original syntax is something you want to use you'll just need to replace the single quotes ' with backticks in order to use template literals. Such as

let Product = event.target.dataset.item;
alert(Product);
let checkboxes = this.template.querySelectorAll(`[data-id="${Product}"]`);

should work as expected

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .