I need to get the ID of an element that was clicked, but I need to to keep all my js and html separate. normally id just use 'this.id' in the html. Any other ways?
Asked
Active
Viewed 1.3k times
7
-
1... you can still refer to the elements from an externally included JS file. – Loktar Apr 22 '12 at 18:32
-
How are you attaching the click handler to this element? – Marc B Apr 22 '12 at 18:37
-
2Start here: https://developer.mozilla.org/en/DOM/event – Teemu Apr 22 '12 at 18:40
-
thanks for replies. I don't know how to attach a handler because I don't know which element will be clicked, so other than making like 20 event handlers i would rather one that attaches to the element i click on – wazzaday Apr 22 '12 at 18:44
-
wazzaday: you can click on anything you want, but either you attach click handlers to the specific elements you want to monitor, or you attach a click handler to EVERYTHING and run a bunch of filtering every time something's clicked. – Marc B Apr 22 '12 at 18:50
3 Answers
12
This is what e.target
is for. You can add an event listener anywhere you want, as long as the click event is allowed to bubble up to it (which happens by default) you can catch it. A basic example:
document.addEventListener('click', function(e) {
alert(e.target.id);
});
Clicking on each will alert its id. Hope this helps :)
<button id="foo">foo</button>
<button id="bar">bar</button>
<button id="baz">baz</button>
EDIT

Darragh Enright
- 13,676
- 7
- 41
- 48
-
1You're welcome :) a standard approach is to attach an event listener to the direct parent of the element(s) you want to listen for; e.g: a `
- ` element containing a bunch of links. One note: if you're listening for clicks on links you might want to add `e.preventDefault();` to your event listener to trap the event and stop it from executing.
-
Oh! I almost forgot to mention one very important point: `addEventListener()` is only supported in IE from version 9. Yes. If you need to support earler versions of IE, read the following: https://developer.mozilla.org/en/DOM/element.addEventListener#Legacy_Internet_Explorer_and_attachEvent - alternatively, you can use a library like jQuery to normalise cross-browser functionality! – Darragh Enright Apr 22 '12 at 22:14
-
1@wazzaday: you should also mark Darragh's answer as the answer which solved your problem. – Petr Felzmann Apr 23 '12 at 12:49
0
Try something like this:
$(document).ready(function () {
$("#someWrapper").each(function () {
$(this).on('click', function () {
alert(this.id);
});
});
});

Petr Felzmann
- 1,271
- 4
- 19
- 39
-
1I'm not seeing a jQuery tag. Was it removed in an early (grace-period) edit, or something? – David Thomas Apr 22 '12 at 19:22
0
window.onclick = e => {
console.log(e.target.id);
}
to get element, tagname, classname , other attributes
window.onclick = e => {
console.log(e.target);
console.log(e.target.tagName);
console.log(e.target.className);
console.log(e.target.id);
}

bhv
- 5,188
- 3
- 35
- 44