-
-
Save eshimischi/d06695a7f3064d6aabf1a443375928cf to your computer and use it in GitHub Desktop.
Simple MutationObserver to understand the behaviour of DOM modifications for a specific AJAX library.
This file contains hidden or 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
// Just a method to log NodeList content | |
var logChildrenModifications = function(type, array) { | |
if (array instanceof NodeList) { | |
for (var i = 0; i < array.length; i++) { | |
if (array.item(i) instanceof NodeList) { | |
logChildrenModifications(type, array.item(i)); | |
} else { | |
console.log(type + ' ' + array.item(i).nodeName); | |
} | |
} | |
} else { | |
console.log(type + ' ' + array.nodeName); | |
} | |
}; | |
// https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutationobserver | |
var observer = new MutationObserver(function(mutations) { | |
mutations.forEach(function(mutation) { | |
if (mutation.type === 'childList') { | |
if (mutation.removedNodes && mutation.removedNodes.length > 0) { | |
logChildrenModifications('removeChild', mutation.removedNodes); | |
} | |
if (mutation.addedNodes && mutation.addedNodes.length > 0) { | |
logChildrenModifications('appendChild', mutation.addedNodes); | |
} | |
if (mutation.previousSibling && mutation.previousSibling.length > 0) { | |
logChildrenModifications('insertBefore', mutation.previousSibling); | |
} | |
if (mutation.nextSibling && mutation.nextSibling.length > 0) { | |
logChildrenModifications('insertAfter', mutation.nextSibling); | |
} | |
} | |
if (mutation.type === 'attributes') { | |
console.log('attribute modified : ' + mutation.attributeName); | |
} | |
}); | |
console.log('---'); | |
}); | |
// The target to observe | |
var targetNode = document.getElementById('theIdToTarget'); | |
// https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutationobserverinit | |
var config = { | |
childList: true, | |
attributes: true, | |
subtree: true | |
}; | |
// Observe the given node with the given config | |
observer.observe(targetNode, config); | |
// To stop the observation !!! Don't forget to disconnect before settign a new observer ! | |
// observer.disconnect(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment