Sometimes, we want to fix HTML encoding lost when attribute read from input field with JavaScript.
In this article, we’ll look at how to fix HTML encoding lost when attribute read from input field with JavaScript.
How to fix HTML encoding lost when attribute read from input field with JavaScript?
To fix HTML encoding lost when attribute read from input field with JavaScript, we can put the HTML string in a text node.
For instance, we write
const htmlEncode = (html) => {
return document.createElement("a").appendChild(document.createTextNode(html))
.parentNode.innerHTML;
};
to define the htmlEncode
function.
In it, we create an a
element with createElement
.
Then we put the html
string in a text node with createTextNode
.
And we append it as the child of the a
element with appendChild
.
Then we return the a
element’s innerHTML
.
Conclusion
To fix HTML encoding lost when attribute read from input field with JavaScript, we can put the HTML string in a text node.