[TIL] e.target vs e.currentTarget 의 차이

이정수·2023년 9월 7일
0

TIL

목록 보기
1/2
post-thumbnail

onClick 이벤트가 발생한 상황에서 event 객체의 event.targetevent.currentTarget의 차이점을 정리하고자 한다.

표준은 targetrhk currentTarget이지만, IE에서는 target은 srcElement로 사용되며 currentTarget은 지원하지 않는다.

작성한 코드는 다음과 같다.

	<div
        style={{ background: 'green' }}
        onClick={(e) => {
          console.log(e.target);
          console.log(e.currentTarget);
        }}
      >
        <span> 하위 span</span>
      </div>

부모요소인 초록색 div에 onClick이벤트룰 걸었고, 클릭을 하면 이벤트의 target과 currentTarget이 콘솔에 출력되도록 하였다.

  1. 녹색div를 클릭했을 경우

target과 currentTarget모두 녹색 div를 가리킨다.

  1. span을 클릭했을 경우

    target은 span, currentTarget은 녹색 div를 가리킨다.

결론

  • currentTarget은 이벤트 리스터가 달린 요소를 가리킨다.
  • target은 실제 이벤트가 발생한 요소(실제로 클릭된)를 가리킨다.

target요소에 직접적으로 이벤트가 걸려있지 않더라도, 이벤트 버블링에 의해 녹색 div의 이벤트를 위임받기에 이벤트를 사용할 수 있는것이다.

mdn에서는

event.currentTarget == the element to which the event handler has been attached.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

이렇게 설명되어 있다.

profile
keep on pushing

0개의 댓글