user1231561
user1231561

Reputation: 3359

e.target.id won't trigger clicking on elements residing within container.children[i].onclick

I have a list of different HTML items:

<ul id="listing">
  <li id="item-0">
    <div class="thumb">Can't get e.target.id clicking here :/</div>
    <div class="text">Can't get e.target.id clicking here :/</div>
  </li>
  <li id="item-1">
    <div class="thumb">Can't get e.target.id clicking here :/</div>
    <div class="text">Can't get e.target.id clicking here :/</div>
  </li>
</ul>

When clicking on <li id="item-0">, <li id="item-1"> I want to get the id of the <li> - my problem though is, if I click on elements within the <li>, then I can't trigger the id.

JSFIDDLE: http://jsfiddle.net/77mawutq/

Code:

var caseListingContainer = document.getElementById("listing");

for (var i = 0, len = caseListingContainer.children.length; i < len; i++)
{

    (function(index){
        caseListingContainer.children[i].onclick = function(e){
            alert(e.target.id);
        }    
    })(i);

}

Upvotes: 1

Views: 94

Answers (1)

Ram
Ram

Reputation: 144699

The target property refers to the element/object that the event was dispatched on and not to the owner of the handler. You can either use the currentTarget property of the event object or the this keyword instead of the target property.

e.currentTarget.id

Upvotes: 2

Related Questions