javascriptdomtargetmutation-events

How can I find where a javascript event is initiated?


I have a JS script which created a new Node and inserts it to the HTML page. I am handling DOM mutation events and can capture DOMNodeInserted event. Inside that function I want to find out the source (i.e. in which part of the HTML has the script function been called) and the target (i.e. in which part the node is being added in the HTML page).

I am able to find the target using event.target, but I am not able to find the source of the event.

For example, consider the following pseudocode HTML page:

<html>
<head>
<script>
   function test() {
      //DOM access
      <div_object>.setAttribute("attr", "value");
   }
</script>
</head>
<body onload="test()">
   <div id="123">
   </div>
</body>
</html>

I want my source to be BODY (because that is were the script is initiated), target should be div(123) (because the attribute is added to div_123.

How can I do this?


Solution

  • Sorry, you can't find out what piece of code caused an event to be triggered, they're completely decoupled. You would have to have the triggering code co-operate by storing the values of its own this/event.target in a variable for the triggered code to pick up later.

    But then if you have co-operation like that, you wouldn't need DOM Mutation Events.

    If you have an event handling layer (as is part of many JS frameworks), you could put the this/target tracking in that layer, so the triggered code could ask “what was the last event that fired, before me?”.

    But I'm not convinced this would be worth it. It's usually best to add your own co-operative hooks that communicate between components; you can't generally rely on DOM Mutation Events since they're not globally and completely supported (or indeed supported at all on IE<9).