Mutation record bounding elements
Demonstrates the difficulty of determining the surrounding elements..
by Tomek
HTML
<ul><li>One</li><li>Two</li><li>Three</li></ul>
JavaScript
// Utilities to get next/previous element siblings.
function tryToEnsurePreviousElement(node) {
return tryToEnsureElement(node, 'previousElementSibling');
}
function tryToEnsureNextElement(node) {
return tryToEnsureElement(node, 'nextElementSibling');
}
function tryToEnsureElement(node, backupProperty) {
if (!node) {
return;
} else if (node.nodeType == Node.ELEMENT_NODE) {
return node;
} else if (node[backupProperty]) {
return node[backupProperty];
}
}
// Prepare the observer.
var observer = new MutationObserver(function(mutations) {
Array.prototype.slice.call(mutations).forEach(function(mutation) {
var content = mutation.removedNodes[0].textContent;
var previous = tryToEnsurePreviousElement(mutation.previousSibling)
var next = tryToEnsureNextElement(mutation.nextSibling);
console.log('Bounding elements for removal of ' + content + ':', previous, next);
});
});
var options = {subtree: true, characterData: true, childList: true, characterDataOldValue: true};
var ul = document.querySelector('ul');
observer.observe(ul, options);
// Remove all items in the list.
while (ul.lastChild) ul.removeChild(ul.lastChild);