본문 바로가기

Javascript

Javascript: MutaionObserver # DOM 변경 감지

728x90
반응형

input, button 등 에서 addEventListener를 통해 이벤트를 감지할 수 있는 것처럼

 

MutationObserver class를 사용하여

HTML 내의 구성(attribute, text, childList) 등이 바뀐 경우, 이를 감지하여 이에 따른 반응 로직을 구현할 수 있다.

 

실제 사용 코드

const searchedBlockMemberUl = document.querySelector('#searchedBlockMemberUl');
const observer = new MutationObserver((mutationsList) => {
    const blockUserInput = document.querySelector('#blockUser');
    for (const mutation of mutationsList) {
        if (mutation.type === 'childList') {
            if (searchedBlockMemberUl.children.length === 0) {
                blockUserInput.style.display = 'block';
            } else {
                blockUserInput.style.display = 'none';
            }
        }
    }
});
observer.observe(searchedBlockMemberUl, { childList: true });

 

 

ChatGPT 설명 및 사용예제

What is MutationObserver in JavaScript?

MutationObserver is a built-in JavaScript class that watches for changes in the DOM (Document Object Model). It listens for mutations such as:

  • Adding, removing, or modifying elements
  • Changing attributes
  • Modifying text content

This allows developers to react to DOM changes efficiently without constantly polling for changes.


How to Use MutationObserver

  1. Create an observer instance.
  2. Define a callback function to handle mutations.
  3. Use the observe() method to start observing a target DOM element.

Example 1: Observe Attribute Changes

 
// Select the target node
const targetNode = document.getElementById('example');

// Create an observer instance
const observer = new MutationObserver((mutationsList) => {
  mutationsList.forEach((mutation) => {
    if (mutation.type === 'attributes') {
      console.log(`Attribute ${mutation.attributeName} changed.`);
    }
  });
});

// Start observing
observer.observe(targetNode, { attributes: true });

// Trigger a mutation
setTimeout(() => {
  targetNode.setAttribute('class', 'new-class');
}, 2000);

 

 

Example 2: Observe Child Element Additions/Removals

const container = document.getElementById('container');

// Callback function
const callback = (mutationsList) => {
  mutationsList.forEach((mutation) => {
    if (mutation.type === 'childList') {
      console.log('Child added or removed:', mutation.addedNodes, mutation.removedNodes);
    }
  });
};

// Create and start observer
const observer = new MutationObserver(callback);
observer.observe(container, { childList: true });

// Simulate DOM changes
setTimeout(() => {
  const newElement = document.createElement('div');
  newElement.textContent = 'New Element';
  container.appendChild(newElement);
}, 2000);

 

Example 3: Observe Text Content Changes

const textNode = document.getElementById('text-node');

// Create an observer
const observer = new MutationObserver((mutationsList) => {
  mutationsList.forEach((mutation) => {
    if (mutation.type === 'characterData') {
      console.log('Text content changed:', mutation.target.data);
    }
  });
});

// Start observing
observer.observe(textNode, { characterData: true, subtree: true });

// Change text content
setTimeout(() => {
  textNode.textContent = 'Updated Text!';
}, 2000);

 

Stopping the Observer

To stop observing, use:

observer.disconnect();

 

 

When to Use MutationObserver

  • Automatically update UI when dynamic changes occur.
  • Implement custom UI components.
  • Build plugins or widgets that react to DOM changes.
728x90
반응형