I currently have something like
<div id="content"></div>
and sequentially add new text to it:
content = document.getElementById(`content`);
content.innerHTML += "<p>The paragraph starts"
(later)
content.innerHTML += " and ends.</p>"
However, it seems that the browser is automatically adding start and closing tags as needed.
The resulting HTML looks like this:
<p>The paragraph starts</p> and ends.<p></p>
The expected result was
<p>The paragraph starts and ends.</p>
Since I'm dealing with a real-time application where the server sequentially sends parts of the document, I don't have the chance to construct a valid HTML before showing it.
Is there any way I can change/avoid the behaviour or work around it?
MVE
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Test</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script type="text/javascript">
window.onload = (event) => {
content = document.getElementById("content")
content.innerHTML = "<p>The paragraph starts"
setTimeout(function(){
content.innerHTML += " and ends.</p>"
}, 3000);
};
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
You could remember the text/html in a variable and replace all the content each time you get more text:
async function mockTextSender() {
let sleep = ms => new Promise(res => setTimeout(res, ms));
sleep(3000);
getText('<p>Some text');
sleep(3000);
getText('and som more');
sleep(3000);
getText(`and that's it</p>`);
}
mockTextSender();
let htmlMemory = '';
function getText(text) {
htmlMemory += text;
$('.myDiv').innerHTML = htmlMemory;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With