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(mutation);
            console.log("I'm between", mutation.addedNodes[0].previousElementSibling, "and", mutation.addedNodes[mutation.addedNodes.length - 1].nextElementSibling);
        }
        if (mutation.removedNodes.length) {
            console.log(mutation);
            console.log("I'm between", mutation.removedNodes[0].previousElementSibling, "and", mutation.removedNodes[mutation.removedNodes.length - 1].nextElementSibling);
        }
    });
});

// configuration of the observer:
var config = {
    childList: true,
    attributes: true
};

// pass in the target node, as well as the observer options
observer.observe(target, config);


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]);
});