user911 user911 -4 years ago 97
jQuery Question

jQuery 'HTML function doesn't work with special characters

I am trying to pass the string

to jQuery's HTML function. It doesn't work because of special character
. I tried encoding/escaping an HTML tag using this escapeHtml function, but I am facing another issue after that.

var escapeHtml = function(theString) {
return theString.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');

It appends HTML-encoded string as text, not as HTML. I saw the below Stack Overflow post, but then it suggests to decode it after encoding. If I do that I am back to square one.

Appending HTML-encoded string as HTML, not as text

I have created a fiddle:

Answer Source

You need to use .text() instead of .html()

        $("p").html("<span id=\"span\"> {A+_\"2OF3_MSF\"} </span>");
<script src=""></script>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download