user3280518
user3280518

Reputation: 111

jQuery don't parse HTML

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

Upvotes: 1

Views: 895

Answers (4)

Sampson
Sampson

Reputation: 268344

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/

Upvotes: 0

soktinpk
soktinpk

Reputation: 3888

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

Upvotes: 0

Adjit
Adjit

Reputation: 10305

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

Upvotes: 1

Goodword
Goodword

Reputation: 1645

how about this?

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

Upvotes: 0

Related Questions