How to prepend text (not HTML) in jQuery?

10,471

Solution 1

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

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

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

Solution 2

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

Solution 3

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>'));
Share:
10,471
ssss
Author by

ssss

Expert in: C#, .NET/IL, JavaScript, HTML/CSS, Unicode; extensive experience with: SQL, Perl, PHP, Delphi, protocols such as HTTP, SMTP, etc.; less experience with: Java, C/C++

Updated on June 09, 2022

Comments

  • ssss
    ssss almost 2 years

    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?

  • Niklas
    Niklas almost 13 years
    What if the original element contains html as well? It will all be lost.
  • James Allardice
    James Allardice almost 13 years
    Indeed... that's a good point! Your method is undoubtedly better.
  • Jay Hardia
    Jay Hardia about 11 years
    hi, this fiddle is not working in case when div has " <div> <script> alert('asfasfsfsfsfsffsafasf'); </script></div>" html. if you have any solution for that plz provide. TIA :)