MutationRecord#nextElementSibling
by Tomek
HTML
<ul id="some-id">
<li>one</li>
<li>two</li>
</ul>
<button id="add">Add new</button>
<button id="delete">Delete first</button>
<p>Check siblings in console output.</p>
JavaScript
// select the target node
var target = document.getElementById('some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.addedNodes.length){
console.log("I'm between", mutation.previousSibling,"and", mutation.nextSibling);
}
if(mutation.removedNodes.length){
console.log(mutation);
console.log("I was between", mutation.previousSibling,"and", mutation.nextSibling);
}
});
});
// configuration of the observer:
var config = { childList: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// -- modify observed element
document.getElementById('add').addEventListener('click', function(e) {
var li = document.createElement("li");
li.innerHTML = "new item";
target.insertBefore( li, target.children[1] );
});
document.getElementById('delete').addEventListener('click', function(e) {
target.removeChild(target.children[0]);
});