JavaScript event.target and event.srcElement

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: How do I determine the event's target element?

Answer: Mouse events of all types (e.g.

click
,
mousedown
,
mouseup
,
mousemove
) have target elements; so do keyboard events (e.g.
keydown
,
keypress
, or
keyup
). For example, when you press a key while typing in a text box, the
keydown
event's target is the
<input>
element defining the text box. When you release a key while typing in a multiline text area, the
keyup
event's target is the
<textarea>
element. When you click an image, the target of the
click
event is the
<img>
element defining the image.

To determine the event's target element, your JavaScript event handler functions can use the following event properties:

  • event.srcElement
    in Internet Explorer
  • event.target
    in most other browsers.

Example: The event handler function

clickHandler
(listed below) combines these techniques to display the HTML tag name of the target element in an alert box:
function clickHandler(e){
 var elem, evt = e ? e:event;
 if (evt.srcElement)  elem = evt.srcElement;
 else if (evt.target) elem = evt.target;
 
 alert (''
  +'You clicked the following HTML element: \n <'
  +elem.tagName.toUpperCase()
  +'>'
 )
 return true;
}

document.onclick=clickHandler;

Demo: click anywhere on this page to see this event handler in action!

Note: Event target element may be the same element that invoked the event handler. However, the event handler may also be invoked for a parent or ancestor element of the target. (This may happen due to event bubbling. For example, the above event handler function

clickHandler
is registered and invoked for the
document
element, which is an ancestor of all specific event target elements such as
<p>
,
<a>
,
<img>
etc.)

See also:

Copyright © 1996-2018, JavascriptFAQ.net.