How do I display an html data piece from mongo db correctly?
Data: The html was encoded
What it shows: Not showing correctly
Code:
JavaScript
x
11
11
1
<script defer>
2
function decodeHtml(html) {
3
var txt = document.createElement("textarea");
4
txt.innerHTML = html;
5
return txt.value;
6
}
7
8
const description = document.getElementById("descontainer")
9
10
description.innerHTML += decodeHtml('<%= post.post.description %>')
11
</script>
Advertisement
Answer
Not really sure why you put that html on a textarea element. But if the content is comming from a database that is contain use generated content, then you probele need an html sanitizer like dompurify.
You will use it like this:
JavaScript
1
14
14
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.6/purify.min.js" integrity="sha512-DJjvM/U3zCRpzrYboJgg23iLHapWcS2rlo7Ni18Cdv+FMs6b3gUF7hQihztj4uVkHHfUwk7dha97jVzRqUJ7hg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
2
3
<script defer>
4
function decodeHtml(html) {
5
6
return DOMPurify.sanitize(html);;
7
}
8
9
const description = document.getElementById("descontainer")
10
11
description.innerHTML += decodeHtml('<%= post.post.description %>')
12
</script>
13
14