Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get an ID of a clicked div element in JavaScript?

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

Thank you for your answers!

like image 511
necker Avatar asked Dec 22 '22 02:12

necker


1 Answers

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.

like image 125
Atanas Korchev Avatar answered Mar 24 '23 05:03

Atanas Korchev