document.getElementById('container').addEventListener('click', function(e) {
if (e.target.classList.contains("btn")) {
console.log('button clicked');
e.stopPropagation(); // 이벤트 버블링 중단
}
});
document.body.addEventListener('click', function() {
console.log('body clicked');
});
<body>
<div id="container">
<button class="btn">Click me</button>
</div>
</body>
버튼 클릭 시:
button clicked
body clicked
조건 통과 못하므로 stopPropagation()도 실행 안 됨 → 버블링 됨
항목 | 설명 |
---|---|
이벤트 위임 | 상위 요소에서 하위 요소의 이벤트를 감지 |
e.target | 실제 클릭된 요소 |
e.stopPropagation() | 이벤트 버블링 중단 |
.classList.contains() | 특정 클래스 있는지 확인 |