JavaScript - Listen to a before node change

With MutationObserver i listen for node insertion in a tree but it run after the node is inserted.

If i want to run a event before the node is inserted to the node what would i do?

ex.

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { subtree: true };

// pass in the target node, as well as the observer options
observer.observe(document.documentElement, config);

The event is like DOMNodeInserted but if i want something like "BeforeDOMNodeInserted"?

Like the "beforescriptexecte" Firefox listener.

Upvotes: 1

Views: 290

Answers (1)

c-smile
c-smile

Reputation: 27460

If i want to run a event before the node is inserted to the node what would i do?

Standard DOM API does not provide you an option to setup a hook on "before content insertion/mutation".

And it has to be a hook (function) but not an event. When you will receive that event (that is asynchronous) it will be too late - mutation already happened.

As an option for you: to define set of DOM mutating functions for the rest of your code. In these function you can do "prefiltering" of content before it will get into the DOM.

Update, here is an example of Node.appendNode "hijacking":

<html>
  <head>

    <script type="text/javascript">
      !function(){
        var pAppendChild = Node.prototype.appendChild;
        Node.prototype.appendChild = function(child) {
          console.log("got appendChild call!");
          pAppendChild.call(this,child);
        }
      }();
    </script>
  </head>
<body>
</body>
    <script type="text/javascript">
      var p = document.createElement("p");
      document.body.appendChild(p);
    </script>
</html>

If you will run the code you will see "got appendChild call!" in console.

Conceptually you can do something like this and redefine standard DOM mutation methods. How practical this would be is another story.

Upvotes: 1

Related Questions