\$\begingroup\$
\$\endgroup\$
1
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');
};
}());
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
-
\$\begingroup\$ Are you unable to use Mutation Observers? \$\endgroup\$forivall– forivall2013年09月16日 17:24:02 +00:00Commented Sep 16, 2013 at 17:24
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
//
// 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?
//
answered Sep 16, 2013 at 3:54
-
\$\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– Nikola Vukovic2013年09月16日 15:35:09 +00:00Commented Sep 16, 2013 at 15:35
default