Reputation: 1559
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,'&').replace(/</g,'<').replace(/>/g,'>');
};
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/
Upvotes: 1
Views: 2485
Reputation: 4511
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>
Upvotes: 4
Reputation: 416
This code is working normally: https://jsfiddle.net/kilotonna/eg4be1gr/1/
$(document).ready(function(){
$("button").click(function(){
$("p").html("{<A+_2OF3_MSF}".replace(/</g, '<'));
});
});
Upvotes: 3