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

后端 未结 2 1370
孤独总比滥情好
孤独总比滥情好 2021-01-13 15:44

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

Thank you for your answers!

相关标签:
2条回答
  • 2021-01-13 16:25

    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 讨论(0)
  • 2021-01-13 16:28

    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.

    0 讨论(0)
提交回复
热议问题