skip to Main Content

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


  1. 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.

    const content = document.getElementById("content")
    let str = "The paragraph starts";
    let p = document.createElement("p")
    
    setTimeout(function() {
      str += " and ends."
      p.innerHTML = str;
      content.append(p)
    }, 3000);
    <div id="content"></div>
    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search