[Javascript] e.target과 e.currentTarget의 차이점

devHagaa·2022년 6월 15일
0

Javascript

목록 보기
3/8

블로그를 보면서 타입스크립트를 공부하다가 e.targete.currentTarget이 다르다는 것을 알고, 무엇이 어떻게 다른지 개념을 이해하고자 정리해본다.

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.

핵심은 currentTarget은 이벤트 핸들러가 부착된 것을 가리킨다는 것이다.
즉, event.target은 부모로부터 이벤트가 위임되어 발생하는 자식의 위치, 내가 클릭한 자식 요소를 반환한다. 하지만 currentTarget은 이벤트가 부착된 부모의 위치를 반환한다.

다음의 예제를 통해 살펴보자. button 태그에 onClick 이벤트가 걸려있다. 그리고 하위에는 span태그가 있다.

<li>
	<button onClick={onLogin}>
    	<span>Button</span>
    </button>
</li>

그리고 버튼을 클릭 했을 때 어떤 것이 반환되는지 확인하기 위해 콘솔을 찍어두었다.

const onLogin = (event) => {
	console.log(event.target);
    console.log(event.currentTarget);
};

실행 결과는 다음과 같다.

정리

event.target은 자식 요소인 span을 리턴하고, event.currentTarget은 부모 요소인 button을 반환하는 것을 알 수 있다.

profile
디자이너인가 퍼블리셔인가 프론트엔드개발자인가 정체성의 혼란을 겪는 개린이

0개의 댓글