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?

  • can you add markup as well? – Pranay Jaiswal Dec 13 '19 at 9:32
  • didnot get what you meant to say exactly – Priyankur Choudhury Dec 13 '19 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 – Pranay Jaiswal Dec 13 '19 at 9:33
  • Hi,I have added HTML snippet in the question itself.Please check – Priyankur Choudhury Dec 13 '19 at 9:38
  • Try with this:- let checkboxes = this.template.querySelectorAll('[data-id="'+Product+'"]'); – sanket kumar Dec 13 '19 at 9:45
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.