본문 바로가기
IT/자바스크립트

자바스크립트 MutationObserver

by Blog37 2024. 4. 29.
반응형

MutationObserver API는 DOM 요소의 "속성", "텍스트", "자식 노드"가 변경 되었는지를 감시하는 API 이다.

[MutationObserver 옵션]

subtree: 대상(target) 노드만 관찰 할건지.. 하위 모든 자식 요소들도 관찰할건지 여부 (true, false)

childList: 자식 노드가 변경 및 추가, 제거 되었는지 관찰 여부 (true, false)

characterData: 텍스트 노드가 변경되었는지 관찰 여부 (true, false)

characterDataOldValue: 텍스트가 변경되기 이전의 값을 가져올건지 여부 (true, false)

attributes: 속성값이 변경 되었는지 관찰 여부 (true, false)

attributeFilter: 특정 속성만 관찰할건지 여부 (class, id, src, data-name)

attributeOldValue: 속성이 변경되기 이전의 값, 가져올건지 여부 (true, false)

 

// DOM 요소가 변경 되었을때.. 실행될 구문 작성
let observer = new MutationObserver(function(mutations){
    mutations.forEach(function(mutation){ 
        console.log(mutation.type);  // 옵션 유형
        console.log(mutation.target);  // 변경된 요소
        console.log(mutation.oldValue);  // 이전 값(attributeFilter, attributeOldValue 값이 true 일때만 유효)
    });
});

// 감시할 DOM 요소 선택
let target = document.querySelector('.target');

// MutationObserver 옵션
let options = {
    subtree: true, 
    childList: true,
    characterData: true, 
    characterDataOldValue: true,
    attributes: true, 
    attributeFilter:["class"],  // (class 속성만 관찰하기)
    attributeOldValue: true,
}

// DOM 요소 감시 시작
observer.observe(target, options);

 

MutationObserver를 중지 시킬려면 disconnect() 를 사용하면 된다.

observer.disconnect();

 

반응형