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

Viewed 79

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?

2 Answers

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>

The correct and officially documented answer to this perplexing conundrum is in @PeterB's response. For anyone looking for a quick fix, just append a space at the end of string, and you're back to sanity.

document.write(x+' ')
Related