What is event.target in JavaScript?

In JavaScript, event.target is a property of an event object that refers to the element that triggered the event. This can be useful for identifying which element an event originated from, which is often necessary when working with event listeners.

Here is an example of how you might use event.target in your code:

// add a click event listener to the button element
document.querySelector('button').addEventListener('click', function(event) {
// the event.target property refers to the element that triggered the event
console.log(event.target);
});

In this example, the click event is attached to a button element. When the button is clicked, the function passed to the addEventListener() method is called, and event.target refers to the button element that was clicked.

You can also use event.target to get or set the value of the element that triggered the event. For example:

// add a change event listener to a form input element
document.querySelector('input').addEventListener('change', function(event) {
// get the value of the input element
const inputValue = event.target.value;
console.log(inputValue)
});

In this example, the change event is attached to an input element. When the value of the input is changed, the function passed to the addEventListener() method is called, and event.target refers to the input element that was changed. The value property of the event.target element is used to get the current value of the input, and then the value property is used to put it in console.

In summary, event.target is a property of an event object that refers to the element that triggered the event. This property can be useful for identifying which element an event originated from, and for getting or setting the value of the element.


October 31, 2022
12184