How to add text (not HTML) in jQuery?

I understand that I can add material to an element using:

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

However, if myText, say, "<span>"I really want this text to appear, but .prepend()instead add an empty span element. What is the recommended way to solve this problem? Do I really have HTML output from the text manually or is there something more elegant?

+5
source share
4 answers

You can create a text index and place the contents there and prependso that:

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

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

+4
source

text prepend :

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

+4

HTML- , :

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

, http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

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

PHP htmlentities Javascript, , PHP-JS: http://phpjs.org/functions/htmlentities:425

, :

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

htmlentities :

$(...).prepend(htmlentities('<span>'));
+1

( ) HTML, : HTML,

:

$(...).prepend(htmlEncode(myText));
0
source

All Articles