title: Javascript function works in unexpected way
body: <p>I've got a javascript function 'doAll', which is supposed to write all the text that was put between <code>&lt;p&gt;, &lt;/p&gt;</code> tags. In my code it is used in two ways.</p>
  
  <p>It works correctly when I just call it at the end of the page. However it should also be triggered out when click-button event occurs. For some reason it doesn't do what it is supposed to do this time. When one click on the button it just prints the inner html of the very first <code>&lt;p&gt;...&lt;/p&gt;</code> html element. </p>
  
  <p>My question is why it works differently in these two situations and what should I do to fix this problem.</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;script&gt;
              function returnList(x)
              {
                  return document.getElementsByTagName(x);
              }
  
              function writeList(x)
              {
                  var i = 0;
  
                  while (x[i])
                  {
                      document.write(x[i++].innerHTML + '&lt;br/&gt;');
                  }
              }
  
              function doAll(x) 
              {
                  writeList(returnList(x));
              }
          &lt;/script&gt;
      &lt;/head&gt;
  
      &lt;body&gt;
          &lt;p&gt;XXX&lt;/p&gt;
          &lt;p&gt;YYY&lt;/p&gt;
          &lt;div style = 'background-color: gray;'&gt;
              &lt;p&gt;YYY&lt;/p&gt;
              &lt;p&gt;XXX&lt;/p&gt;
          &lt;/div&gt;
  
          &lt;button type = 'button' onclick = "doAll('p')"&gt;
              Click me!
          &lt;/button&gt;
  
          &lt;script&gt;
              document.write('&lt;br/&gt;');
              doAll('p');
          &lt;/script&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Here is the 'output':<br/>
  XXX<br/>
  YYY<br/>
  YYY<br/>
  XXX<br/>
  <br/>
  XXX<br/>
  YYY<br/>
  YYY<br/>
  XXX<br/>
  <br/>
  And here is what one can see after clicking the button:<br/>
  XXX</p>