JQuery - tag attribute with escaped html is automatically canceled

I have this div with a data attribute that may contain escaped html value

<div id="test" data-title="&lt;script&gt;alert(&quot;Hello&quot;);&lt;/script&gt;"></div> 

Now, when I read the value of the data attribute, it is not automatically displayed. For example, the following code will trigger an alert.

 $(document).ready(function(){ $("#test").append($("#test").data("title")); }); 

See jsfiddle http://jsfiddle.net/FJTW8/3/

Why does he get unlimited and what solution.

+4
source share
3 answers

try it

 $(document).ready(function(){ //alert($("#test").data("title")); $("#test").append(escape($("#test").data("title") ) ); }); 
0
source

This code will work:

 $(document).ready(function(){ $("#test").text($("#test").data("title")); }); 

Because .append () is the same as .html ();

0
source

the answer is not quite right you should do this:

 $(document).ready(function(){ $("#test").append(htmlEntities($("#test").data("title") ) ); }); function htmlEntities(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } 

See jsfiddle http://jsfiddle.net/FJTW8/16/

0
source

All Articles