Search code examples
jqueryencodinghtml-parsingcdatahtml-encode

HTML tags encoded when appending CDATA tag


In my page, there is a div in which I have to display html from javascript. So in javascript, I append the CDATA tags so that the html is displayed as data. Following is the code I have used

var htmlCode = '<h>testing html</h>';
htmlCode = '<![CDATA[' + htmlCode+ ']]>';
$('myDiv').html(htmlCode);

This actually displays testing html]]> as the last > is converted into &gt; when I assign it to the html of the div. Any idea how to overcome this problem

Thanks in advance


Solution

  • CDATA is used in XML files. it means the content inside is treated as text. jQuery's .html() turns <![CDATA[<h into <!--[CDATA[<h-->, which is a comment. It then ignores the closing </h> tag as the opening one is missing. So, it displays testing html]]>.

    If you want to display HTML as text, just use .text() instead of .html(). It will escape it for you, so that it won't be parsed by the browser.

    var htmlCode = '<h>testing html</h>';
    $('#myDiv').text(htmlCode);
    

    EDIT: You said you wanted the HTML to be parsed, then just use.html.

    var htmlCode = '<h>testing html</h>';
    $('#myDiv').text(htmlCode);
    

    The CDATA is not needed in either case.