How do you get the clicked div element id in JavaScript?

So my question is how to get the id of the item that was just clicked? (Javascript)

Thank you for your responses!

+4
source share
2 answers

You can use the target element (in all browsers except IE) and srcElement (in IE) to get the element with a click:

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 careful with event bubbles. target may not be what you expect.

+9
source

The "target" attribute of the event object passed to your event handler (or, in the case of IE, configured as a global variable) will be a reference to the affected element. If you configure event handlers using Prototype, then:

  function clickHandler(ev) { var id = ev.target.id; // ... } 
+2
source

Source: https://habr.com/ru/post/1310603/


All Articles