2

Currently, I am stuck in a situation to modify the DOM in LWC using the querySelectorAll function.

Here the {team.item.Description__c} field having the DOM details and saved in string form into the salesforce database.

team.html

<template if:true={teamRecords} >
    <template for:each={teamRecords} for:item="team" for:index="index">
        <div class="descArea" lwc:dom="manual" key={team.item.id}> </div>
    </template>
</template>

team.js

this.teamRecords.map((item, index) => {
    this.template.querySelectorAll('.descArea').forEach(element => {
        element.innerHTML = item.item.Description__c; //Contains HTML elements
    });
})

The .descArea is a class name of a div inside a loop in LWC component and I want to change the content of the div using the querySelectorAll function.

  • 1
    During which stage of the lifecycle are you trying to access the DOM elements? – Jayant Das Feb 27 at 13:56
  • Can you please specify what's not working? Isn't the querySelectorAll call returning the divs? Or is the HTML not displaying correctly? – muenzpraeger Feb 28 at 8:53
  • @muenzpraeger I want to add some HTML element which is stored into item.item.Description__c property into the div with class name "descArea". – Tarique Shamim Feb 28 at 9:00
  • Understood. Your question looks like you're having issues with querySelectorAll, because it's all bold. – muenzpraeger Feb 28 at 9:13
  • Yes, I want to select all the Div elements and then add some more elements into it. – Tarique Shamim Feb 28 at 10:03
3

It's not clear to me why you need to do this imperatively. Would the following accomplish the same thing?

<template if:true={teamRecords} >
    <template for:each={teamRecords} for:item="team" for:index="index">
        <div key={team.item.id}>
            {team.item.Description__c}
        </div>
    </template>
</template>
  • I have updated the question with more details related to {team.item.Description__c} field, which I want to show on the LWC. – Tarique Shamim Feb 28 at 8:00
  • Because what if I want to dynamically make changes to the Shadow DOM? – Mr. B Oct 23 at 22:29

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.