Search code examples
javascriptmutation

Get Index position of element mutation happened on


My question is about DOM mutations. Years ago, web developers were able to handling changes made to DOM (known as DOM Mutations).

I used this function to check if an element has been removed from the DOM. Also I was able to get the index position index() of the element before it remove from the DOM:

function NodeRemovedEventTrigger() {
jQuery( "body" ).bind(
    "DOMNodeRemoved",
    function( objEvent ){
        // Append event to log display.
        var elem = $(objEvent.target);
        if(elem.hasClass('feed-container')) {
            var i = elem.index();
            console.log(i);//get index position of the element
        }
    }
);

}

Since DOMNodeRemoved is deprecated and not supported in some browsers, How do I achieve a function similar to the above function with MutationObserver() method. My emphasis is getting the index position

what I tried doesn't seem to work for me:

// select the target node
var target =document.getElementById('post-line');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
 mutations.forEach(function(mutation) {

    if (mutation.removedNodes) {
        //if the element removed has class='post-container' , then get the index position
        var elem    =   mutation.removedNodes;
        console.log(elem.index());//get index position
    }
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true,removedNodes:NodeList[0]};

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

HTML:

<div id="post-line">

<div class="post-container">
    <div><span></span></div>
</div>

<div class="post-container">
    <div><span></span></div>
</div>

<div class="post-container">
    <div><span></span></div>
</div>
</div>

Thank you.


Solution

  • I think you can use mutation.previousElement to get index of the element that was previous to removed one. Then just add 1 to get removed element index:

    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if (mutation.removedNodes) {
          var elem = mutation.removedNodes;
          var prevElement = $(mutation.previousSibling.previousElementSibling);
          var removedIndex = prevElement.index() + 1;
          console.dir(removedIndex);
        }
      });
    });