In JavaScript, events have a target attribute to identify which DOM element was the target of the event. When we listen for events on a specific DOM element we can provide a callback function that is called when the event is triggered. This callback function takes the event as its first argument. This event object contains the target of the event. Here's a quick example showing how to access the target.
The markup:
<button>Click me</button>
And the JavaScript:
$(function() {
$("button").on('click', function(event) {
console.log(event.target);
});
});
Note: Even though we are using jQuery, as it stands the event.target attribute will be a vanilla JavaScript DOM object, not a jQuery object.
In the above example, the target would be the actual button that was clicked.
When we get into nested DOM elements this becomes a little bit more interesting. Take our example from the previous step. Suppose we log the target for each div.
$(function() {
$("#outer").on('click', function(e) {
console.log($(e.target).attr('id'), $(this).attr('id'));
});
$("#middle").on('click', function(e) {
console.log($(e.target).attr('id'), $(this).attr('id'));
});
$("#inner").on('click', function(e) {
console.log($(e.target).attr('id'), $(this).attr('id'));
});
});
The above code simply logs the id of the target and the id of this - this being the element we're listening to. A click on the #inner element will log this:
inner inner
inner middle
inner outer
Each line shows target this.
As expected, the target doesn't change. Even though the event is bubbled up and triggered on parent elements, the target remains the actual element that was clicked on. However, this provides access to the element we're listening to. As we see, inner inner is first showing that the event on the #inner element was triggered first, and obviously #inner is the target as well.