How to prepend text (not HTML) in jQuery?

Timwi picture Timwi · Jun 20, 2011 · Viewed 9.7k times · Source

I realise that I can prepend stuff to an element using:

$(...).prepend(myText);

However, if myText is, let’s say, "<span>", I actually want that text to appear, but .prepend() would instead prepend an empty span element. What is the recommended way to solve this? Do I really have to HTML-escape the text manually or is there something more elegant?

Answer

Niklas picture Niklas · Jun 20, 2011

You can create a textnode and put the contents there and prepend that:

$('div').prepend(document.createTextNode("<span>"));

example: http://jsfiddle.net/niklasvh/gCKHe/