MutationObserver

MutationObserver는 웹 페이지의 DOM(Document Object Model) 변화를 감지하고 이에 대한 콜백 함수를 실행하는 JavaScript API다. DOM의 변경 사항을 모니터링하고, 해당 변경에 대해 실시간으로 반응하거나 필요한 작업을 수행할 때 사용된다.

활용

  • 동적 콘텐츠 감지: 웹 페이지가 동적으로 변경되는 경우(예: AJAX 요청으로 콘텐츠를 추가하거나 변경하는 경우) 이 변경 사항을 감지하고 적절한 조치를 취할 수 있다.
  • UI 업데이트: UI가 변경되거나 엘리먼트의 속성이 변경될 때, 이에 따른 업데이트 작업 수행
  • 폼 필드 감시: 폼 필드의 값이 변경될 때 입력 유효성 검사나 자동완성 기능을 활성화하거나 비활성화

구성 및 예시

<!DOCTYPE html>
 
<html>
  <head>
    <style>
      .container {
        width: 200px;
        height: 200px;
        background-color: lightblue;
      }
    </style>
  </head>
  <body>
    <div class="container"></div>
 
    <script>
      // 대상 엘리먼트와 옵션을 설정
      const target = document.querySelector('.container')
      const options = {
        attributes: true, // 속성 변경 감지
        childList: true, // 자식 엘리먼트 추가/삭제 감지
        characterData: true, // 텍스트 내용 변경 감지
        subtree: true // 하위 엘리먼트까지 모두 감지
      }
 
      // 콜백 함수 정의
      function handleMutation(mutationsList, observer) {
        for (let mutation of mutationsList) {
          if (mutation.type === 'childList') {
            console.log('Child nodes have been added or removed.')
          } else if (mutation.type === 'attributes') {
            console.log('Attributes have been changed.')
          } else if (mutation.type === 'characterData') {
            console.log('Text content has been changed.')
          }
        }
      }
 
      // MutationObserver 인스턴스 생성
      const observer = new MutationObserver(handleMutation)
 
      // 대상 엘리먼트와 옵션을 사용하여 감시 시작
      observer.observe(target, options)
 
      // 변화를 시뮬레이션하기 위해 엘리먼트에 변화를 가해본다.
      target.textContent = 'Hello, world!'
    </script>
  </body>
</html>

위의 예시에서는 .container 엘리먼트의 변화를 감시하고, 변화 타입에 따라 콜백 함수가 실행되는 방법을 보여준다. 이를 통해 DOM 변경 사항을 감지하고 필요한 작업을 처리할 수 있다.