views:

60

answers:

2

So my question is how to get an ID of an element that has just been clicked? (JavaScript)

Thank you for your answers!

+2  A: 

The "target" attribute of the event object passed to your event handler (or, in the case of IE, set up as a global variable) will be a reference to the element affected. If you're setting up your event handlers with Prototype, then:

 function clickHandler(ev) {
   var id = ev.target.id;
   // ...
 }
Pointy
+5  A: 

You can use the target element (in all browsers except IE) and srcElement (in IE) in order to retrieve the clicked element:

function click(e) {
  // In Internet Explorer you should use the global variable `event`  
  e = e || event; 

  // In Internet Explorer you need `srcElement`
  var target = e.target || e.srcElement;

  var id = target.id;
}

However be aware of event bubbling. The target may not be the element you expect.

korchev
`target` is the element where the event originates. in standards browsers, `currentTarget` is the element attached to whatever function is running. ie doesn't have an equivalent to `currentTarget` that I'm aware of.
lincolnk
this will sound like a stupid question but i cant figure out what to feed my function with? is "e" supposed to be an event and when i am calling a function i should do sth like: click(onclick)? and after it i could use the variable id?
necker
You have to make your function be an event handler for something, probably a container element surrounding the elements you're interested in.
Pointy
@necker if you're doing it inline: `<div id="foo" onclick="click(event);" />`if you do it with `addEventListener`/`attachEvent`, `e` is the default parameter and will be the relevant event instance. prototype probably has a wrapper method using these calls to add your handlers.
lincolnk