Search code examples
javascriptjquerydocument.writehtml-escape-characters

Why does an entity escape at the end of the string not show up for document.write(x) on domready?


var target = '<p><img alt=\"\" src=\"upfiles\/54591303758197437.jpg\" \/><\/p>'
$(function(){
    var x=$('<div/>').text(target).html();
    alert(x);
    document.write(x)
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I show the escaped string contained html tags and write in webpage.
The escaped string in the alert window is right, but after closing the alert window you can ony see (screenshot):

<p><img alt="" src="upfiles/54591303758197437.jpg" /></p

Where is the last > ?

Why <p><img alt="" src="upfiles/54591303758197437.jpg" /></p> won't show up in the webpage?


Solution

  • I had the same symptom on Chrome 69 (Windows).

    Managed to fix it by adding a document.close() call, as recommended by MDN:

    target = '<p><img alt=\"\" src=\"upfiles\/54591303758197437.jpg\" \/><\/p>'
    $(function(){
        x=$('<div/>').text(target).html();
        alert(x);
        document.write(x);
        document.close();
    });
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>