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
1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

0

how about this?

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

Comments

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

Comments

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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.