What is event.target in JavaScript?
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 accessibleconsole.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
elementthat 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.
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.