Skip to content
Advertisement

How access the original observed node by MutationObserver when subtree is true?

How can I access the original target node when using MutationObserver with options childList and subtree set to true?

On the callbacks, the target is changed to whatever node has mutated, and this is expected as per the MDN documentation, but my intention is to always be able to look at the original node, so I can evaluate if it is overflowing.

Why is this my intention?

Well, it’s because I have noticed that, depending on the edge case, the ResizeObserver won’t trigger, while the MutationObserver with the configs as per stated above, will trigger. Therefore I would like to access the original node in this scenario so I can calculate if it is overflowing.

So I do not care about what exactly is going on inside the subtree. I just want to use this callback to access the original node and evaluate if it is overflowing.

export const setupObserver = ({
  observer,
  callback, 
  node,
}) => {
  const observer = new MutationObserver(callback);
  
  // I want to somehow access the original node always when the callback is executed
  observer.observe(node, {
      attributes: true,
      childList: true,
      subtree: true,
    });
}     

Of course, if I know how to find the original node inside the callback function, it works fine. But it would cause a dependency, which is something I would like to avoid.

For example:

const callbackFunction = useCallback(
    (records: MutationRecord[]) => {

// ignore the internals of this function.
// the point is that getting by ID works inside the callback
// allowing me to calculate if it is overflowing or not
// but this would cause a dependency, which I would like to avoid
        checkOverflow({
          element: document.getElementById('overflowing-test'),
          state: isOverflow,
          setState: setIsOverflow,
        });
    }
    , [isOverflow],
  );

Advertisement

Answer

It can be done by binding the node to callback when creating the observer:

export const setupObserver = ({
  observer,
  callback, 
  node,
}) => {
  const observer = new MutationObserver(callback.bind(null, node));
  ...   

Then access it as first callback argument:

const callbackFunction =
    (node: HTMLElement, records: MutationRecord[]) => {
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement