Prevent jQuery from escaping html entities

ladar picture ladar · Oct 14, 2011 · Viewed 9.2k times · Source

I have some simple html editor. Let's say that user types following:

<p>Ok, this just &amp; sucks :) &ndash;</p>

and it is saved to some variable:

var content = "<p>Ok, this just &amp; sucks :) &ndash;</p>";

Now, somewhere I'm using jQuery to append this text to some element:

$(this).html(content); // where content is the string above

The problem is that it is escaped:

<p>Ok, this just &amp;amp; sucks :) &amp;ndash;</p>

How can I achieve to have the exact string with &amp ; and &ndash ; and also to have < and not &lt ; because I need html tags?

Edit: more details added

Answer

Ned Batchelder picture Ned Batchelder · Oct 14, 2011

The problem is not that jQuery is escaping the entities. I think if you use console.log to write the content string, you'll see that your editor is returning escaped entities to you.

The whole point of .html() vs .text() is that .html() is for HTML that will be treated as HTML.