Timwi
Timwi

Reputation: 66604

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?

Upvotes: 7

Views: 11391

Answers (4)

James Allardice
James Allardice

Reputation: 166061

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

Upvotes: 4

J. Bruni
J. Bruni

Reputation: 20490

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

Upvotes: 1

Town
Town

Reputation: 14906

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

Upvotes: 0

Niklas
Niklas

Reputation: 30012

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

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

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

Upvotes: 10

Related Questions