How to insert HTML as Text

There’s no need to escape the characters. Simply use createTextNode:

var text = document.createTextNode('<p>Stuff</p>');
document.body.appendChild(text);

See a working example here: http://jsfiddle.net/tZ3Xj/.

This is exactly how jQuery does it (line 43 of jQuery 1.5.2):

return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

Leave a Comment