user911 user911 -4 years ago 97
jQuery Question

jQuery 'HTML function doesn't work with special characters

I am trying to pass the string

"{<A+_2OF3_MSF}"
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:

https://jsfiddle.net/1aktfzm8/

Answer Source

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

$(document).ready(function(){
    $("button").click(function(){
        $("p").html("<span id=\"span\"> {A+_\"2OF3_MSF\"} </span>");
        $('#span').text();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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