setInterval(function(){},1000)과 같이 사용하다가 작동하는 요소의 존재유무를 확인하여 사용하기에는 불편함이 있어 검색해보니 MutationObserver
라는 객체를 찾게되어 해당 요소를 정리하고자 한다.
<script>
// MutationObserver 설정
const observer = new MutationObserver(function(mutationsList) {
mutationsList.forEach(function(mutation) {
// 새로운 <p> 요소가 추가된 경우
if (mutation.type === 'childList') {
$('#totalProducts tbody td p.product').each(function() {
// 이미 내용이 추가되지 않은 경우에만 추가
if ($(this).find('.reserve_info').length === 0) {
$(this).prepend('<strong class="reserve_info" style="display:block;color:#f00 !important;">예약판매 4.4 출고</strong>');
}
});
}
});
});
// 관찰할 대상 설정
const targetNode = document.getElementById('totalProducts');
// MutationObserver가 관찰할 옵션 설정
const config = { childList: true, subtree: true };
// 관찰 시작
observer.observe(targetNode, config);
</script>
MutationObserver 생성
MutationObserver
는 DOM의 변화를 관찰하는 객체입니다. 이 객체는 DOM 요소가 변경될 때마다 콜백 함수를 호출하게 되며, 그 콜백 함수 안에서 어떤 변화가 일어났는지 알 수 있습니다.mutationsList
는 DOM에서 발생한 여러 변화들을 담고 있는 배열입니다. 각 변화는 mutation
객체로 되어 있습니다.mutation.type === 'childList'
mutation.type
은 어떤 종류의 변화가 일어났는지 알려줍니다. 여기서 childList
는 DOM 트리에서 자식 노드의 추가 또는 삭제를 의미합니다. 즉, 자식 요소가 추가되거나 삭제될 때 해당 코드가 실행됩니다.$('#totalProducts tbody td p.product').each(function() { ... })
each()
는 jQuery의 반복문으로, #totalProducts tbody td p.product
셀렉터에 맞는 모든 <p class="product">
요소를 순회하며 아래 내용을 실행합니다.if ($(this).find('.reserve_info').length === 0)
$(this).find('.reserve_info')
는 현재 순회 중인 p.product
요소 내부에서 .reserve_info
클래스를 찾습니다.length === 0
은 .reserve_info
요소가 없으면 조건이 참이 되어, .reserve_info
가 추가되지 않은 경우에만 아래의 prepend
작업을 수행합니다.$(this).prepend('<strong class="reserve_info" style="display:block;color:#f00 !important;">예약판매 4.4 출고</strong>');
prepend()
는 해당 요소의 맨 앞에 HTML을 삽입하는 jQuery 메서드입니다. 이 코드는 p.product 요소의 맨 앞에 <strong class="reserve_info">예약판매 4.4 출고</strong>
를 추가합니다.const targetNode = document.getElementById('totalProducts');
targetNode는 우리가 MutationObserver로 관찰할 DOM 요소입니다. 이 예제에서는 #totalProducts라는 ID를 가진 요소를 지정합니다.
const config = { childList: true, subtree: true };
config
객체는 MutationObserver
가 어떤 종류의 변화를 관찰할지 설정하는 옵션입니다.childList
: true: 자식 요소의 추가/삭제를 감지합니다.subtree
: true: targetNode와 그 하위 모든 자식 요소에서 변화를 감지합니다. 즉, #totalProducts 안의 p.product가 추가되거나 삭제될 때마다 관찰할 수 있습니다.observer.observe(targetNode, config);
이 코드로 MutationObserver가 targetNode 요소의 변화를 감지하기 시작합니다. config 옵션을 통해 자식 노드의 추가나 삭제가 있을 때마다 콜백 함수가 호출됩니다.
1. DOM 변화를 감지
#totalProducts 내에서 p.product 요소가 추가되거나 변경될 때마다 MutationObserver가 이를 감지합니다.
2. 조건 체크
p.product 내부에 .reserve_info 요소가 이미 존재하는지 확인하고, 없으면 새로 추가합니다.
3. 반복적으로 실행
MutationObserver는 지속적으로 변화를 감지하며, p.product가 DOM에 추가될 때마다 내용이 중복되지 않게 prepend 작업을 실행합니다.
이 방법은 setInterval을 사용하지 않으면서도, DOM 요소의 추가/변경에 실시간으로 반응하여 필요한 작업을 수행할 수 있게 해줍니다. DOM 변화가 있을 때마다 처리하므로 불필요한 주기적 호출을 피할 수 있습니다.