Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

What is event.target in JavaScript?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

When an event is fired, the element that fires the event is known as the emitter. This element is what we call the target. So, the target property of that event object refers to the event emitter.

Syntax

The target property can only be obtained if the event of an element is being listened to.

element.addEventListener("input", function(event){
//event.target is now accessible
console.log(event.target)
})

In the code above, the element’s input event is being listened to, which makes event.target accessible.

Importance of event.target

It is necessary to have the target property when an event is fired. We can do the following with the target property of the event.

  • Get the element that fired the event.
  • Access the properties of the element.
  • Modify some properties of the element, such as the CSS, the attributes, etc.

Code

The code below shows how an input element that fires the oninput event is listened to and event.target is retrieved. The code also shows some capabilities of having event.target at our fingertips.

Console

As the input box is inserted with data, the element and its value property is logged to the console. The CSS color property is also modified. These are just a few use cases of event.target.

RELATED TAGS

javascript
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring