DEV Community

elifrie
elifrie

Posted on

Explaining event.target

My name is Eli Friedlander. As I begin my software engineering journey there are many topics that I could dig deeper into. Throughout the past weeks I have often been confused about the syntax, usage, functionality, etc. of different nuances in javascript, HTML, and CSS. I’ve found solace in blog posts such as this. I hope this can help clear any confusion you may have surrounding the use of “event.target”.

In short - event.target is a property of an event object that targets the specific element that triggers the event. This becomes useful when you are looking to return the value of the element that triggered the referenced event.

When to use:

As mentioned above - the target property is used to retrieve any attribute or property of the event it is attached to. Let’s say we have an event listener for an input box like below:

Image description

First, we are targeting the input box with ID ‘input’ and naming it ‘inputBox’ so that we may attach an event listener to it.

Second, we attach an event listener that is triggered when the input box is interacted with.

So what’s next? Now that we have our event listener we can use the target property to:

  1. Retrieve the element of the fired event
  2. Access different properties of the fired event
  3. Modify properties and attributes of the element

Syntax:

The Syntax for using the target property on events is not too different from other syntaxes that leverage dot notation; ‘target’ is added after the event with dot notation like below:

Image description

These are a few examples of how you would use event.target to access different attributes of the event, such as the ‘value’ or a specific CSS element. In the first console.log we are simply returning the event object. The second console returns the actual value of the event which can prove useful when you’re looking to attach a command to a value return. The last example portrays how you can use event.target to modify CSS attributes.

In summary, event.target is a way to access the value or specific attributes of an event when an event listener is attached.

I hope this helped clear up some doubts you may have around how / when to use event.target!

Top comments (0)