2

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?

2
  • Try this (a little hack) stackoverflow.com/a/19381852/3639582 Commented May 3, 2015 at 18:54
  • @ShaunakD Coincidentally enough, I just found the same method here and used it in my updated answer below. Commented May 3, 2015 at 18:59

1 Answer 1

1

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/

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

7 Comments

I appreciate your help, but you think this is the best solution? Because if it's, I will for the first time think that jQuery is missing something here.
I considered mentioning in my answer that this is kind of cheating, because it is. jQuery has a $.parseHTML method, but it only converts the characters to their text equivalents-- exactly what your previous code does. See here for an example of this function. I don't even begin to pretend to know everything about jQuery, but it does appear that the function that you need is nonexistent.
On second thought, I may have managed to solve your issue. See my edited answer above.
Yes... Looks like this is nonexistent. I'll accept your answer in few time if doesn't appear anything 'official' for this question... I prefer the first solution you gave-me because the second one, if the HTML code isn't escaped, it will mess things up.
@user3810691 Refer to my updated answer for a working demo that does not use replace.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.