1

I have a string which is essentially html elements, and I'm using jQuery to try to append this string to a div:

var content = '<div>Test</div>';
$('div').append(content);

Is there a way in JavaScript or jQuery to make it so it doesn't parse the string so in my div I get:

<div>Test</div>

instead of

Test
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user3280518
  • 111
  • 2
  • possible duplicate of [Escaping HTML strings with jQuery](http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery) – elzi Nov 06 '14 at 22:47

4 Answers4

1

You can use jQuery .text() function to put strings into HTML elements. If you were to use the .html() function it would simply put test

Adjit
  • 10,134
  • 12
  • 53
  • 98
0

how about this?

var content = '<div>Test</div>';
$('div').text(content);
Goodword
  • 1,565
  • 19
  • 27
0

Try wrapping it in a smaller div and call text:

$('div').append($('<div>').text(content));

This might look cleaner with

$('<div>').text(content).appendTo('div');

Or, if you are okay with overwriting all of the old content in the div:

$('div').text(content);

If you do not want to wrap it inside a new div, use

$('div').append($('<div>').text(content).html());
soktinpk
  • 3,778
  • 2
  • 22
  • 33
0

You can add it as a text node instead:

var content = "<div>Text</div>";
$("body").append( document.createTextNode( content ) );

Fiddle: http://jsfiddle.net/jonathansampson/ojn2L0vL/

Sampson
  • 265,109
  • 74
  • 539
  • 565