How to escape HTML tags as HTML entities with JavaScript?

Spread the love

Sometimes, we want to escape HTML tags as HTML entities with JavaScript.

In this article, we’ll look at how to escape HTML tags as HTML entities with JavaScript.

How to escape HTML tags as HTML entities with JavaScript?

To escape HTML tags as HTML entities with JavaScript, we create a text node and get its innerHTML content.

For instance, we write

const escapeHTML = (html) => {
  return document
    .createElement("div")
    .appendChild(document.createTextNode(html)).parentNode.innerHTML;
};

to define the escapeHTML function.

In it, we create a div with createElement.

And then we call appendChild with a text node we create from the html string.

Then we get its parent node with parentNode.

And we get the escaped HTML with innerHTML.

Conclusion

To escape HTML tags as HTML entities with JavaScript, we create a text node and get its innerHTML content.

Leave a Reply

Your email address will not be published. Required fields are marked *