user3810691
user3810691

Reputation: 531

jQuery append not rendering HTML escaped code

I'm using this jQuery command:

 $('.body-container').append(bodyPart.content).html();

to append HTML content into my body. If "bodyPart.content" is something like:

<strong>Bold</strong>

It works nicely, and show me on my browser:

Bold

But if it's:

&lt;strong&gt; Bold &lt;/strong&gt;

it shows me on the browser:

<strong> Bold </strong>

What to do here to jQuery understand escaped HTML code?

Upvotes: 2

Views: 2667

Answers (1)

IronFlare
IronFlare

Reputation: 2322

You can replace the &lt; and &gt; with the proper characters using replace like so:

$("button").click(function(){
    var inp = $("input").val().replace(/&lt;/gi,"<").replace(/&gt;/gi,">");
    $('.body-container').append(inp).html();
});

https://jsfiddle.net/IronFlare/w7edc0cv/


With the help of this question, I think I may have managed to solve your issue (hopefully):

$("button").click(function(){
    $('.body-container').append($('<div/>').html($("input").val()).text());
});

https://jsfiddle.net/IronFlare/w7edc0cv/3/

Upvotes: 1

Related Questions