How to know, where exactly MutationRecord happened (multiple targets)?

1.2k views Asked by At

I trying to observe a group of elements. Quantity of elements can be various : from 1 to 10.

$observedElements = document.querySelectorAll('em.price'); 
// in that time length will be 3.

// $observedElements[0]  is a   '<em class='price'>10.15</em>'
// $observedElements[1]  is a   '<em class='price'>35.00</em>'
// $observedElements[2]  is a   '<em class='price'>48.95</em>'

So..

var observer = new MutationObserver(function(MutationRecord) {
    MutationRecord.forEach(function(MutationRecord) {
        if (MutationRecord.type == 'characterData')  {  
            console.log ('got it ... in elem. № ? ');   
            // which element is affected by this mutation? [0], [1] or [2] ?    
        };
    });
});

var observerConfig = { attributes: false, childList: true, characterData: true, subtree: true, };

for (var i = 0; i < $observedElements.length; i++) {
    observer.observe($observedElements[i], observerConfig);
};

When value in some element became changed, an MutationRecord.type characterData is received. In my example right now $observedElements[1] changes from '35.00' to '25.00'

But how i can know that this changes was in emelent $observedElements[1] ? In received target.textContent i gon only text value.

1

There are 1 answers

3
loganfsmyth On BEST ANSWER

MutationRecord.target already points to the item that changed, so you could find the root with

function findObserver(mutationRecord) {
  for (var i = 0; i < $observedElements.length; i++) {
    if ($observedElements[i].contains(mutationRecord.target)) {
      return $observedElements[i];
    }
  }
  return null;
}