1

I working on a client side app. I have been working non-stop for the past two days trying to figure what was going on. My code is a bit too long to post to where I can explain what my problem is, I have narrowed where the problem is to the following scenario/question. Here is what I have:

<html>
    <head>
    </head>
    <body>
        <a href="#" id="hyper">Link</a>
    </body>
</body>
</html>
<script type="text/javascript">
    document.getElementById("hyper").onclick = function(){alert("Link clicked!");};
    document.body.innerHTML = document.body.innerHTML;
</script>

This code works fine with out the without document.body.innerHTML = document.body.innerHTML;.

Why doesn't the event handler fire after body.innerHTML = body.innerHTML; even though the object, object.id are still the same and have loaded before the JavaScript?
I have viewed the live DOM and all is the same.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Babiker
  • 18,300
  • 28
  • 78
  • 125

2 Answers2

1

When you re-assign body.innerHTML, even if it's itself, the innerHTML changes and the DOM resets. That means, the a#hyper was re-created and its onclick became destroyed.

Self-assignment identity (note: said as a Haskeller) may not exist with getters and setters.\

Ming-Tang
  • 17,410
  • 8
  • 38
  • 76
1

There is a great answer here - basically the DOM is regenerated when Javascript re-inserts the HTML string. The generated DOM may look the same, but programmatic references in Javascript have all been set to new addresses.

A solution for keeping event handlers and methods is here:

javascript cloneNode and properties

Community
  • 1
  • 1
Ben
  • 54,723
  • 49
  • 178
  • 224
  • Thanks Steve. I read the other posts and understood that even though the source is the same but the object to which the event handler has been set is destroyed. But i failed to try to mimic the solution in my scenario. Can you write a snippet as to how it would using my example? – Babiker Nov 18 '10 at 02:52