title: Dynamically add html elements and event handlers by using Javascript
body: <p>I added 3 div elements in the form and add event handler for each of them dynamically. It is supposed to popup a message showing that div's id. However, no matter which box I click, it popups the last div's id which is 10175.</p>
  
  <p>Any input will be appreciated.</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;style type="text/css"&gt;
    .empty
            {
              background-color: green;
            }
     .safebox
            {
          margin-left: auto;
          margin-right: 20px;
          margin-top: 20px;
          text-align: center;
          float: left;
          width: 60px;
          height: auto;
            }
  &lt;/style&gt;
   &lt;script type="text/javascript"&gt;
      function ClickMe(elem){
          alert(elem.id);
      };
  
     window.onload=function(){
      var tempdiv = document.createElement('div');
      var text = document.createTextNode('0173');
      tempdiv.className='safebox empty';
      tempdiv.appendChild(text);
      tempdiv.setAttribute('id','10173');
      tempdiv.appendChild(text);
      document.getElementById('pagewarpper').appendChild(tempdiv);
  
      var currentdiv = document.getElementById('10173');
      if (currentdiv.addEventListener){
         currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
      }
      else {
        currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
      }
  
      var tempdiv = document.createElement('div');
      var text = document.createTextNode('0174');
      tempdiv.className='safebox empty';
      tempdiv.appendChild(text);
      tempdiv.setAttribute('id','10174');
      tempdiv.appendChild(text);
      document.getElementById('pagewarpper').appendChild(tempdiv);
  
      var currentdiv = document.getElementById('10174');
      if (currentdiv.addEventListener){
         currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
      }
      else {
        currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
      }
  
      var tempdiv = document.createElement('div');
      var text = document.createTextNode('0175');
      tempdiv.className='safebox empty';
      tempdiv.appendChild(text);
      tempdiv.setAttribute('id','10175');
      tempdiv.appendChild(text);
      document.getElementById('pagewarpper').appendChild(tempdiv);
  
      var currentdiv = document.getElementById('10175');
      if (currentdiv.addEventListener){
         currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
      }
      else {
        currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
      }
        }
       &lt;/script&gt;
     &lt;/header&gt;
    &lt;body&gt;
   &lt;form&gt;
   &lt;div id="pagewarpper"&gt;
  &lt;/div&gt;
    &lt;/form&gt;
   &lt;/body&gt;
  </code></pre>
  
  <p></p>