JavaScript | event target과 currentTarget의 차이점

Positive Ko·2020년 11월 15일
29

JavaScript

목록 보기
14/28

이 글에서는 React onClick 이벤트 상황에서 event.target과 event.currentTarget의 차이점을 정리해본다.
흔히 쓰는 event.target은 이해할 수 있다. 다만 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태그가 있다.

내가 span(Google)을 클릭했을 때 정확히 어떤 것이 반환되는지 알기 위해 콘솔을 찍어두었다.

자 결과는, 다음과 같다.


event.target은 자식 요소인 span을 리턴하고, event.currentTarget은 부모 요소인 button을 반환하는 것을 알 수 있다.
반드시 구분해서 적절히 사용하도록 하자.




profile
내 이름 고은정, 은을 180deg 돌려 고긍정 🤭

3개의 댓글

comment-user-thumbnail
2021년 12월 10일

안녕하세요 혹시 코드 이미지 어떻게 저렇게 만들었는지 여쭤봐도 될까요?

답글 달기
comment-user-thumbnail
2022년 1월 21일

click 동작의 대상인 button을 기준으로 한다면 event.target은 자식을 return하는게 맞는데
event.curretTarget이 button을 반환하면 부모가 아니라 자기자신을 return한다고 해야 설명이 맞는 거 같네요.
중간에 기준을 바꾸셔서 다른 사람이 볼 땐 헷갈릴 수도 있겠어요.

답글 달기
comment-user-thumbnail
2022년 4월 17일

감사합니다~

답글 달기