I have html like below:
<div onclick=" callJavascript()">
<span id="abc"> abc </span>
<span id="def"> def </span>
<span id="ghi"> ghi </span>
</div>
When I click 'abc' or 'ghi', is there anywhere inside function callJavascript()
, to find out which span id I clicked on ?
Yes there is :
For Not IE browsers :
function callJavascript ( e ) {
alert(e.target); // the DOMElement object
alert(e.target.id); // the object's id
}
For IE :
function callJavascript ( e ) {
alert(e.srcElement); // the DOMElement object
alert(e.srcElement.id); // the object's id
}
You must nevertheless adapt your html :
<div onclick=" callJavascript(e)"> // replace "e" by "event" in IE.
<span id="abc"> abc </span>
<span id="def"> def </span>
<span id="ghi"> ghi </span>
</div>
If you want a more complete reference, here it is : http://www.quirksmode.org/js/events_properties.html
Wow ! May I mention, for better accuracy, your event listener should not be on the div element, instead, it may be triggered by the span elements themselves. The target or srcElement being the one on which the event occurs.
It's not part of the question, but it's worth saying : I usually prefer to avoid event attachment in html code since it causes scope problems and forces you, as in your case, to manually pass the event parameter.
You have to add the event param to your onclick listener to have the event accessible within your listener.
<div onclick="callJavascript(event)">
Then use the target
or srcElement
property to get the DOM element.
function callJavascript(e) {
var target = e.srcElement || e.target;
alert(target.id);
}
Working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With