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
  • 51,252
  • 26
  • 196
  • 186
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
  • 9,708
  • 11
  • 49
  • 93
0

how about this?

var content = '<div>Test</div>';
$('div').text(content);
Goodword
  • 1,407
  • 19
  • 26
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,628
  • 2
  • 20
  • 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
  • 259,174
  • 73
  • 529
  • 557