2

I'm using lwc:dom="manual" and querySelector to capture and display the text content but it does not work.

HTML code

<h2 class="slds-truncate" title={record.Name}>
    <a href="#" data-id={record.Id}>
        <div class="first-el" lwc:dom="manual"></div>
    </a>
</h2>

JS code

renderedCallback() {
    let firstEl = document.querySelector(".first-el");
    console.log('First El',firstEl);
    firstEl.innerHTML = '<span class="slds-truncate" data-id={record.Id}>First Element</span>';
    }

or

connectedCallback() {
    let firstEl = document.querySelector(".first-el");
    console.log('First El',firstEl);
    firstEl.innerHTML = '<span class="slds-truncate" data-id={record.Id}>First Element</span>';
    }

Because it needs to be rendered when the page load so I tried to do it within the connectedCallback and renderedCallback but the result returned the same. And the record is a public property (@api record) that is passed from Parent component. I'm not sure if this effect the error.

Log result image enter image description here

Thank you so much!

1 Answer 1

1

You can't using binding in your manual dom.

Evaluate those expressions in the javascript, then add your element.

let firstEl = document.querySelector(".first-el");
const html = `<span class="slds-truncate" data-id="${record.Id}">First Element</span>`
firstEl.innerHTML = html;

Make sure that in your full code record.Id is defined. Where are you getting this value from?

If record.Id has not been retrieved yet, consider putting the above code in the handler for your record data call.

EDIT If you use case is not more complicated than this, then I'd skip manual dom altogether and just do this:

<a lwc:if={record.Id} href="#" data-id={record.Id}>
  <div class="first-el">
    <span class="slds-truncate" data-id={record.Id}>First Element</span>
  </div>
</a>

EXTRA EDIT

You need to make sure that rendered callback is not called in a loop. Every time you make a change to the UI, the callback will be invoked etc...

Use a Boolean to prevent this:

rendered = false;
renderedCallback() {
  if(rendered){
    return;
  }
  //do other logic
}
2
  • Hi @Caspar Harmer, my use case is more complicated! I removed the record.Id to make it work so there is nothing relevant to record anymore but it even does not log First El this time. My update code: firstEl.innerHTML = '<span class="slds-truncate">First Element</span>';
    – Pam
    Commented Aug 18, 2023 at 0:49
  • you need to prevent a rendercallback loop - see my addendum Commented Aug 18, 2023 at 1:54

You must log in to answer this question.

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