0

I have a variable in my js file, let's say myCode = "<h1>HELLO</h1>";

myCode displays as <h1>HELLO</h1> in HTML. . . I want it to render the h1 tag and just display HELLO

3
  • Doing this may expose you to security concerns, depending on where this markup comes from. It is intentionally not supported or easy to do using LWC. If you only have a limited number of options, you could use multiple templates with conditional rendering.
    – Phil W
    Commented Jun 16, 2023 at 20:57
  • @PhilW - so this is actually related to a question I posted about rendering an img tag from a formula field. Thought I'd try and simplify original question
    – mackmama
    Commented Jun 16, 2023 at 21:43
  • I noticed that question but did not read it.
    – Phil W
    Commented Jun 16, 2023 at 21:52

1 Answer 1

1

LWC sanitizes what's rendered in the page to prevent security risk, that's why the default behavior is to display it as text instead of as a markup element.

Anyway, since some third-party libraries may need to manipulate the DOM, the framework exposes the lwc:dom="manual" directive

HTML

<div class="myClass" lwc:dom="manual">
 </div>

JS

modifyDom() {
     const hello = '<h1>HELLO</h1>';
     this.template.querySelector('.myClass').innerHTML = hello;
}

If you want to just render some text, you should leverage lightning-formatted-rich-text to pass HTML tags in your component markup via its value attribute.

You must log in to answer this question.

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