How to correct the output of the following code?
<p>when executing, the <code>&lt;p&gt;</code> inside <code>"demo"</code> and the <code>document.write("hello")</code> are displayed after the output of the for loop. I want both the statements to print before the <code>for</code> loop, how can I do that?</p>

<pre><code>&lt;html&gt;
&lt;body&gt;
  &lt;div id="main"&gt;
  &lt;p&gt;1&lt;/p&gt;
  &lt;p&gt;2&lt;/p&gt;
  &lt;p&gt;3&lt;/p&gt;
&lt;/div&gt;

&lt;p id="demo"&gt;&lt;/p&gt;
  &lt;p&gt;11&lt;/p&gt; &lt;!-- wrong o/p here --&gt;
&lt;script&gt;
  document.write("hello"); // and also wrong here
  var x = document.getElementById("main");
  var y = x.getElementsByTagName("p");
  var len = y.length
  for(var i=0;i&lt;=len;i++) {
     document.getElementById("demo").innerHTML += y[i].innerHTML + " &lt;br&gt;"; 
  } 
 &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Output:</p>

<pre><code>1

2

3

1 
2 
3 

11

hello
</code></pre>