Insert HTML String As Text in Javascript

Published on February 24, 2021

The append() & prepend() methods can be used to insert HTML string inside a given element. Both methods parse given HTML string as text and create Text node.

These methods escape HTML characters in the string and can be used to insert un-escaped user generated content in the page.

append() will insert the HTML string after the last child of the parent.

prepend() will insert the HTML string before the first child of the parent.

let html = '<p>Demo</p>';

let html = '<p>Demo</p>';


PS: createTextNode() is also a popular way of creating a Text node and escape HTML. However this involves first creating the Text node and then inserting it. With append() & prepend(), both can be achieved in a single line.

In this Tutorial
    Loading Comments