CODE/Javascript
MutationObserver (DOM 변경사항 감지) | Zerocho
AGAL
2021. 7. 2. 14:30
반응형
[출처 : https://www.zerocho.com]
// 감시할 대상
var target = document.getElementById('zerocho-changeable');
// 옵저버
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
// 감시할 내용 설정
var config = {
attributes: true,
childList: true,
characterData: true,
subtree: true || null,
attributeOldValue: true || null,
characterDataOldValue: true || null,
};
// 감시할 대상 등록
observer.observe(target, config);
// 대상에 변경 발생
document.getElementById('attributes').addEventListener('click', function() {
target.setAttribute('class', 'zerocho-newclass');
});
// 대상에 변경 발생
document.getElementById('childList').addEventListener('click', function() {
target.textContent = 'zerocho';
});
옵저버 옵션
config = {
addedNodes: [], // 추가된 자식 노드,
attributeName: null, // 변경된 속성명
attributeNamespace: null, // 변경된 속성네임스페이스
nextSibling: null, // 다음 형제 태그
previousSibling: null, // 이전 형제 태그
oldValue: null, // 변경전 값
removedNodes: [], // 제거된 자식 노드
target: Element, // 대상 태그
type: 'attributes' || 'childList' || 'characterData' // 어떤 종류가 변경되었는지
}
옵저버 중지
observer.disconnect(); // 감시 중지
반응형