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

后端 未结 2 1401
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题