Note that there are some explanatory texts on larger screens.

plurals
  1. POwhat to use instead of document.write or InnerHTML?
    primarykey
    data
    text
    <p>Say I have an html code like this:</p> <pre><code>&lt;script&gt; // just an example function to get data from input function getNumber(form) { var userInput = new Number; // convert form values into numbers userInput = Number(form.enteredNumber.value); return userInput; } function countNumbers(form) { var lastNumber = getNumber(form); // the last number to be counted for (i = 1; i &lt;= lastNumber; i++) { //count the numbers document.write(" "+i); // put the numbers on the page if((i % 10) == 0) { document.write("&lt;br&gt;"); // insert a break 10 by 10 to create a block of numbers } } } &lt;/script&gt; &lt;form&gt; Enter a number:&lt;input type="text" name="enteredNumber"/&gt; &lt;input type="button" value="Count!" onClick="countNumbers(this.form);"/&gt; &lt;/form&gt; &lt;div id="numberBlocks"&gt;&lt;/div&gt; </code></pre> <p>So if user entered 25 the result would be close to what I want, like this:</p> <p>1 2 3 4 5 6 7 8 9 10</p> <p>11 12 13 14 15 16 17 18 19</p> <p>20 21 22 23 24 25</p> <p>But the document.write clears the entire page, and I don't want that. If I use:</p> <pre><code>document.getElementById('numberBlocks').InnerHTML = i; document.getElementById('numberBlocks').InnerHTML = '&lt;br&gt;'; </code></pre> <p>it will merely replace the contents of the element, I don't want that either. the output will be:</p> <p>nothing or a number&lt;--- since the last element will be a break tag or a number.</p> <p>How do I do this, in a way, the content of page isn't destroyed and the output result is what I want?</p> <pre><code>document.getElementById('numberBlocks').InnerHTML += i document.getElementById('numberBlocks').InnerHTML = " " + "&lt;br&gt;"; </code></pre> <p>won't work either, since they will overwrite the element instead of adding new ones.</p> <p>And these two would generate the same result as document.write</p> <pre><code>res = document.getElementById('numberBlocks'); res.innerHTML = res.innerHTML +" "+i; res = document.getElementById('numberBlocks'); res.innerHTML = res.innerHTML + "&lt;br&gt;"; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload