Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend text (not HTML) in jQuery?

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?

like image 813
Timwi Avatar asked Jun 20 '11 12:06

Timwi


2 Answers

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

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

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

like image 122
Niklas Avatar answered Nov 11 '22 20:11

Niklas


You can use the text function instead of prepend, and simply add the original text to the end of the new text:

$("#elementID").text("<span>" + $("#elementID").text());

like image 41
James Allardice Avatar answered Nov 11 '22 19:11

James Allardice