Search code examples
javascriptmutation-observers

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?


Solution

  • 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.