Organizational Research By

Surprising Reserch Topic

is it possible to append to innerhtml without destroying descendants onclick fu


is it possible to append to innerhtml without destroying descendants onclick fu  using -'javascript,html'

In the following example code, I attach an onclick handler to the span containing the text "foo". The handler is an anonymous function that pops up an alert().

However, if I append to the parent node's innerHTML, this onclick handler gets destroyed -- clicking "foo" fails to pop up the alert box.

Is this fixable?

<html>
 <head>
 <script type="text/javascript">

  function start () {
    myspan = document.getElementById("myspan");
    myspan.onclick = function() { alert ("hi"); };

    mydiv = document.getElementById("mydiv");
    mydiv.innerHTML += "bar";
  }

 </script>
 </head>

 <body onload="start()">
   <div id="mydiv" style="border: solid red 2px">
     <span id="myspan">foo</span>
   </div>
 </body>

</html>

    
asked Sep 9, 2015 by rajesh
0 votes
2 views



Related Hot Questions



Government Jobs Opening


...