e.target과 e.currentTarget의 차이

들블리셔·2022년 4월 22일
0

e.target과 e.currentTarget의 차이점



html

<div class="box">
        <div class="btn1">버튼1</div>
        <div class="btn2">버튼2</div>
</div>




e.target

클릭한 요소에 이벤트가 발생

document.querySelector('.box').addEventListener('click', e => {
  console.log(e.target);
  
  //box 클릭시
  //<div class="box">버튼1</div> 출력
  
  //btn1 클릭시
  //<div class="btn1">버튼1</div> 출력
  
  //btn2 클릭시 
  //<div class="btn2">버튼2</div> 출력
})

즉, 이벤트리스너가 걸린 요소는 box이지만,
box를 포함해서 그 안에 자식으로 있는 요소를 클릭하면 출력하게 됩니다.





e.currentTarget

Eventlistener가 걸려있는 요소에 이벤트 발생

document.querySelector('.box').addEventListener('click', e => {
  console.log(e.currentTarget); 
  
  // <div class="box"></div>
})

e.target과 다르게 box안 자식요소(btn1, btn2)를 클릭해도 이벤트 걸린 요소만 출력






얕은 지식으로 제가 이해한 바로 작성해보았습니다.
틀린게 있다면 댓글로 알려주시면 좋은 가르침 받겠습니다!

profile
나의 공부방

0개의 댓글