-
-
Save ralphholzmann/378415 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Rough implementation, untested, etc | |
// Will obviously fail when non-overridden methods are used to change the DOM | |
(function($){ | |
$.fn.isAncestorOf = function( elem ) { | |
// If parent and child element are the same, return false | |
if (this[0] == elem[0]) return false; | |
// Initially set result to false | |
var isAncestor = false, | |
parent; | |
// Find closest parent with same tag name of parent | |
while (( parent = elem.closest( this[0].tagName )).length ) { | |
// If parent found is same as parent | |
if (( isAncestor = this[0] == parent[0] )) { | |
// Break and return | |
break; | |
} else { | |
// Keep trying on next parent | |
elem = parent.parent(); | |
} | |
} | |
return isAncestor; | |
} | |
// All "DOM modifying" methods (probably not complete). | |
var methods = 'unwrap html wrapAll wrapInner append appendTo html prepend prependTo text after before insertAfter insertBefore'.split(' '); | |
$.each( methods, function( i, method ) { | |
// Store a reference to the original method. | |
var orig = $.fn[ method ]; | |
// Override the original method. | |
$.fn[ method ] = function(){ | |
var args = arguments, | |
elems = []; | |
// For each selected element... | |
this.each(function(){ | |
// Store the initial HTML. | |
var html = this.innerHTML; | |
// Execute the original method. | |
orig.apply( $(this), args ); | |
// If the HTML has changed, add this element to the list of elements. | |
if ( this.innerHTML !== html ) { | |
elems.push( this ); | |
} | |
}); | |
// Unique the elements list. | |
elems = $.unique( elems ); | |
// Filter out child-parent relationships | |
// using double for loop (is there a better way thats not big O n^2?) | |
// | |
// Had to use for loops (as opposed to .each) because we're | |
// modifying the contents of the array within the loop. | |
for ( var i = 0, q, elem; i < elems.length; i++ ) { | |
for ( q = 0; q < elems.length; q++ ) { | |
if ( $(elems[i]).isAncestorOf( $(elems[q]) )) { | |
elems.splice(i, 1); | |
q = 0; | |
} | |
} | |
} | |
// Trigger a custom 'domchanged' event that will bubble! | |
$(elems).trigger( 'domchanged' ); | |
return this; | |
}; | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment