title: how to binding a event handler to a element being created?
body: <p>In my page,I have to create some elements dymamiclly according use's operation,for example,when user click a button,I will create a new div,but I want to add a click handler to this div:</p>
  
  <pre><code>function createNewDiv(){
    var str="&lt;aid='na'&gt;xxx&lt;/a&gt;";
    //add click handler to this a
    var ele=document.getElementById("na");
    if(ele.attachEvent){
      ele.attachEvent("onclick",function(){xxxx});
    }else if(ele.addEventListener){
      ele.addEventListener("click",function(){xxx},false);
    }
    document.getElementById("con").innerHTML="s";
  }
  </code></pre>
  
  <p>When I run this code,I get the error:</p>
  
  <p>ele is not defined.</p>
  
  <p>Maybe this is caused that when I use the </p>
  
  <pre><code>var ele=document.getElementById("na")
  </code></pre>
  
  <p>THe html dom is under building,so it can not find the element.(I think this is why we use the jquery.ready(xxx).</p>
  
  <p>If so,is there any idea to make it work?</p>
  
  <p>I use Prototype 1.4 in my app.</p>
  
  <hr>
  
  <p>Thanks for all the answers.</p>
  
  <p>Now use the <code>&lt;a&gt;</code> instead the <code>&lt;div&gt;</code></p>
  
  <p>However for somea reason,I can not use the dom to build my element,that's to say,I can not use:</p>
  
  <pre><code>var div_n=document.createElement("a");
  a.id="na";
  ......
  </code></pre>
  
  <p>Instead,I have to use the:</p>
  
  <pre><code>var s="&lt;a id='na'&gt;xxx&lt;/a&gt;";
  
  //append this created link to the existed container
  document.getElementById("con").innerHTML=s;
  
  //then how to add the click handler to the `a#na`?
  </code></pre>