Ahmad Alfy
Ahmad Alfy

Reputation: 13371

Getting reference to element being observed with MutationObserver

I am using MutationObservers to watch changes happening to multiple DOM nodes (basically adding to their subtrees or removing the nodes overall).

The observer works fine because I am using subtree option. The only problem is that I cannot get reference to the parent element that has the mutation observer attached to

const mutationObserver = new MutationObserver(mutationRecords => {
  mutationRecords.forEach(mutationRecord => {
    const addedNodesLength = mutationRecord.addedNodes.length;
    for (let i = 0; i < addedNodesLength; i++) {
      const node: Element = mutationRecord.addedNodes[i];
      // I need to check the parent of node that is being observed
    }
  });
});

I searched MDN and I cannot find any reference if that's possible. Any idea if that can be done?

Upvotes: 6

Views: 6401

Answers (2)

0xENDER
0xENDER

Reputation: 109

This should do it:

const observer = new MutationObserver(function(mutationsList, observer){
  for(let mutation of mutationsList){
    console.log(mutation.target);
  }
});

Upvotes: -1

gyimi
gyimi

Reputation: 282

mutationRecord.target gives you the parent element, at least according to this

I have tested it only on Firefox but it seems to be working.

Upvotes: 9

Related Questions