3
\$\begingroup\$

I'm building a mini-app that will display when changes to the DOM have been made by JavaScript. I have all of the functions that I can think of listed in the code. Is there a way to consolidate the functions into one, and have the overrides still function correctly?

var DomChanges = (function() {

  var a = Element.prototype.appendChild
  , b = Element.prototype.removeChild
  , c = Element.prototype.insertBefore
  , d = Element.prototype.insertAfter
  , e = Element.prototype.insertAttribute
  , f = Element.prototype.removeAttribute
  , g = Element.prototype.replaceChild
  , h = Element.prototype.createElement;

  Element.prototype.appendChild = function(){
    DomChange('appendChild', arguments);
    a.apply(this, arguments);
  };

  Element.prototype.removeChild = function() {
    DomChange('removeChild', arguments);
    b.apply(this, arguments);
  };

  Element.prototype.insertBefore = function() {
    DomChange('insertBefore', arguments);
    c.apply(this, arguments);
  };

  Element.prototype.insertAfter = function() {
    DomChange('insertAfter', arguments);
    d.apply(this, arguments);
  };

  Element.prototype.insertAttribute = function() {
    DomChange('insertAttribute', arguments);
    e.apply(this, arguments);
  };

  Element.prototype.removeAttribute = function() {
    DomChange('removeAttribute', arguments);
    f.apply(this, arguments);
  };

  Element.prototype.replaceChild = function() {
    DomChange('replaceChild', arguments);
    g.apply(this, arguments);
  };

  Element.prototype.createElement = function() {
    DomChange('createElement', arguments);
    h.apply(this, arguments);
  };

  function DomChange (ftype, arguments) {
    console.log('Dom has been changed');
  };

}());
\$\endgroup\$
3
\$\begingroup\$
//
// maybe this:
//
"appendChild removeChild insertBefore insertAfter insertAttribute removeAttribute replaceChild createElement"
.split(" ")
.forEach(
    function ( ftype ) {
        var corefn = this[ftype]
        this[ftype] = function () {
            DomChange( ftype, arguments );
            return corefn.apply( this, arguments );
        };
    },
    Element.prototype
);
//
//  do you overide .innerHTML somehow?
//
\$\endgroup\$
  • \$\begingroup\$ It misses .innerHTML embeds, so you don't get notified when that occurs... Posible solution would be to run the timer fn on elements of interest checkig the state of the property, and running a callback when modification is spotted. I've posted the timer factory on SO here (stackoverflow.com/questions/18544237/… ), so you might consider using it if want to spot the mod. \$\endgroup\$ – Nikola Vukovic Sep 16 '13 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.