开发者

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

开发者 https://www.devze.com 2022-12-31 01:18 出处:网络
So my question is how to get an ID of an element that has j开发者_StackOverflowust been clicked? (JavaScript)

So my question is how to get an ID of an element that has j开发者_StackOverflowust been clicked? (JavaScript)

Thank you for your 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.


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;
   // ...
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消