PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] Why don't even handlers of dynamically inserted objects fire, even if they existed before the JavaScript ran?

 October 15, 2022     dom, dom-events, javascript     No comments   

Issue

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.


Solution

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.\



Answered By - Ming-Tang
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing