Get clicked element id without putting js code in html

I need to get the id of the element that was clicked, but I need to save all my js and html separately. Usually id just uses 'this.id' in html. Any other ways?

+7
source share
3 answers

This is for e.target . You can add an event listener anywhere, until the click event can go to it (which happens by default), you can catch it. Basic example:

 document.addEventListener('click', function(e) { alert(e.target.id); }); 

Clicking on each of them will warn its identifier. Hope this helps :)

 <button id="foo">foo</button> <button id="bar">bar</button> <button id="baz">baz</button> 

EDIT

http://jsfiddle.net/95NZ8/

+12
source

Try something like this:

 $(document).ready(function () { $("#someWrapper").each(function () { $(this).on('click', function () { alert(this.id); }); }); }); 
0
source
 window.onclick = e => { console.log(e.target.id); } 

to get the attributes element, tagname, classname,

0
source

All Articles