[JavaScript] Checking the Target Element

You might want to hook up the handler function to multiple elements. How can you get the reference of the element that triggered the event?

1. window.event.srcElement

To get which element that triggers the event, the IE legacy code uses the “window.event.srcElement” property.

document.getElementById("clickBtn").onclick = onClicked;

function onClicked() {
  alert(window.event.srcElement.type); // returns "button"


2. target

Another way to access the target element is to use the standard event object’s “target” property.

$(document).ready(function () {
  document.getElementById("clickBtn1").onclick = onClicked;

function onClicked(e) {
  alert(e.target.type); // returns "button"


3. jQuery

jQuery’s event wrapper object works in all browsers.

$(document).ready(function () {

function onClicked(e) {
  alert(e.target.type); // returns "button

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s