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>
2
Answers
You can use createElement and have a variable with the content to create the paragraph. Then in your setTimeout add to your innerHTML then append to the content div.
You could remember the text/html in a variable and replace all the content each time you get more text: