Javascript: get element ID from event

When you bind an event listener with addEventListener, it's called with this referring to the element you bound the event on. So this.id will be the id of the element (if it has one).

alert('The id of the element you clicked: ' + this.id);

But you're breaking that with this line:

tags[i].addEventListener('mousedown', function(e){ tagClick(e) }, false);

...because you're putting an extra function in the middle, then calling tagClick without setting this. There's no need for that extra function, change that to:

tags[i].addEventListener('mousedown', tagClick, false);

...so this doesn't get messed up. Or alternately if you prefer to have the extra function, ensure this is maintained using Function#call:

tags[i].addEventListener('mousedown', function(e){ tagClick.call(this, e) }, false);

...but there's no reason to do that with the tagClick function shown.

The (standard) event object also has the properties target (which may not be the element you bound the event on, it may well be a descendant) and currentTarget (which will be the element you bound the event on). But this is convenient and reliable if you use addEventListener (or even attachEvent, on IE).


You can get the target of the event with e.target.

However keep in mind that some browsers consider text nodes to be a target, so try something like this:

var t = e.target;
while(t && !t.id) t = t.parentNode;
if( t) {
    alert("You clicked element #"+t.id);
}

This will find the first element that actually has an ID.

Happy New Year!

EDIT: On second thought, if it's the "tag" element itself you want to refer to, just use this. In an event handler, this refers to the element that actually has the handler. Although in this case you'll need to change your handler to ('mousedown', tagClick, false)

Or better still:

document.body.addEventListener("mousedown",function(e) {
    var t = e.target;
    while(t && t.nodeName != "TAG") { // note, must be uppercase
        t = t.parentNode;
    }
    if( t) {
        alert("You clicked on #"+t.id);
    }
},false);

Fewer event handlers is always better.


document.getElementById("body").addEventListener("mousedown", function(e){
 console.log(e.target.id);      
});

enjoy.