7

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?

Timwi
  • 65,159
  • 33
  • 165
  • 230

4 Answers4

10

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

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

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

Niklas
  • 29,752
  • 5
  • 50
  • 71
  • hi, this fiddle is not working in case when div has "
    " html. if you have any solution for that plz provide. TIA :)
    – Jay Hardia Feb 21 '13 at 10:47
4

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());

James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

HTML entities are ok, in my opinion:

$(...).prepend('&lt;span&gt;');

You may automate the entities with the tip found at http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

$(...).prepend($('<div/>').text('<span>').html());

If you also want to create PHP's function htmlentities in Javascript, you may use the code available at PHP-JS project: http://phpjs.org/functions/htmlentities:425

Or you may simplify by wrapping the previous tip in a function:

function htmlentities(string) {
  return $('<div/>').text(string).html();
}

In both cases, you would use the htmlentities function like this:

$(...).prepend(htmlentities('<span>'));
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
0

You could implement HTML encode (and decode) functions, like this accepted answer: HTML-encoding lost when attribute read from input field

and then do:

$(...).prepend(htmlEncode(myText));
Community
  • 1
  • 1
Town
  • 14,706
  • 3
  • 48
  • 72