admin管理员组

文章数量:1295268

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?

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?

Share asked Apr 23, 2018 at 22:55 Ahmad AlfyAhmad Alfy 13.4k6 gold badges68 silver badges102 bronze badges 1
  • There's no way as you can see in the specification. Simply save the element in a variable. – woxxom Commented Apr 24, 2018 at 4:02
Add a ment  | 

2 Answers 2

Reset to default 9

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.

This should do it:

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

本文标签: javascriptGetting reference to element being observed with MutationObserverStack Overflow