I use code like this to dynamically create some link-based controls:
<script type='text/javascript'> function BuildControls (id, ...) { var div = document.getElementById (id); /* some stuff with var sp=document.createElement('span'); */ var a = document.createElement ('a'); a.innerHTML = on ? 'Cancel' : captions_do[i]; a.className = class_do; a.style.display = on2 ? '' : 'none'; a.id = 'iAccept'+id+'_'+i+'Control'; div.appendChild (sp); div.innerHTML+='<br />'; div.appendChild (a); a.onclick = function () {alert ('wtf')}; div.innerHTML+='<br />'; } </script> ... <div id='someid'></div> <script type='text/javascript'> BuildControls ('someid', ...); </script>
So when I click on the link, it does nothing. If I call a.onclick() explicitly, it works. What is wrong?
That is syntactical sugar for:
Which makes it clearer what is happening: you just serialised the entire contents of the div to HTML, added a tiny string, and parsed the results back into HTML. Even if it worked flawlessly, that’d be really inefficient.
When you serialise an element, you lose any non-attribute-based information attached to it, including JavaScript properties, event handlers and listeners. Say goodbye to your onclick.
Never use “innerHTML+=”. It is always a mistake.
An alternative is to set innerHTML on a standalone div not attached to the document, then append its childNodes one-by-one to the element where you really want it.
But for something this simple, you should just be using the standard DOM methods: