Search code examples
javascripthtmlxsslit-element

JavaScript / Lit-element safe way to parse HTML


I am getting some html from my server that I want to put into my page. However I want it to be sanitized (just in case).

However I am not quite sure how to do this.

So far I've tried:

<div .innerHTML="${body}"></div>

Since that should parse it as HTML but I am not 100% sure that this is the best way.

I have also looked at online sanitizers but haven't been able to find any that match my project (Lit-element web component).

Is there a better way to parse HTML and if so how?


Solution

  • Take a look at the DOMParser interface API

    document.getElementById('my-target').append(new DOMParser().parseFromString(data, 'text/html').body.children);