Get the index position of an item mutation happened

My question is about DOM mutations. Several years ago, web developers were able to handle changes made to the 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 of an element before it was removed 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 can I achieve the same functionality as described above using the MutationObserver () method . My emphasis is on the position of the index

what I've tried doesn't 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.

+3


source to share


1 answer


I think you can use mutation.previousElement

to get the index of an element that was previously deleted. Then just add 1

to get the removed item:



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

      

0


source







All Articles