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
- Create an observer instance.
- Define a callback function to handle mutations.
- 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
반응형
'Javascript' 카테고리의 다른 글
Javascript: 클라이언트 단에서의 대용량 데이터 처리 성능 이슈 개선 # 비동기처리 # Chunk # requestAnimationFrame (rAF) (2) | 2024.12.13 |
---|---|
Javascript: arrow function (0) | 2024.05.22 |
Javascript: Animation 백그라운드 동작 중지 # requestAnimationFrame (0) | 2023.09.11 |
Javascript: slide # 무한 슬라이드 (0) | 2023.09.10 |
Javascript: Parsing HTML #select #checkbox #radio (0) | 2023.03.31 |