Javascript: get element ID from event

Viewed 35353

How to get the ID of an element passed as (e)?

window.addEventListener('load', function(){

    var tags = document.getElementsByClassName("tag");
    for (i=0; i<tags.length; i++){
    tags[i].addEventListener('mousedown', function(e){ tagClick(e) }, false);
    }

}, false);

function tagClick(e){

    /* here I'm gonna need the event to cancel the bubble and the ID to work with it*/

    alert('The id of the element you clicked: ' + [?object].id);

    [?object].className='newClass';

    e.stopPropagation();
    e.cancelBubble = true;
}

I need to get the element/object inside tagClick so I can change its properties

html:

<div class="tag">
    <img src="/images/tags/sample.jpg"/>
    <label class="tagLabel">Sample</label>
</div>

See, the element with the event attached is the div, but ig gives me the image object instead when using e.srcElement.

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

enjoy.

Related