Get Clicked <li> from <ul onclick>

The object which was actually clicked is

event.target

inside the onclick callback. What you are trying to do is a good idea, and it is known as event delegation.

http://jsfiddle.net/VhfEh/


You can use event.target for this:

JS:

// IE does not know about the target attribute. It looks for srcElement
// This function will get the event target in a browser-compatible way
function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement; 
}

var ul = document.getElementById('test');
ul.onclick = function(event) {
    var target = getEventTarget(event);
    alert(target.innerHTML);
};

HTML:

<ul id="test">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

Example: http://jsfiddle.net/ArondeParon/2dEFg/5/

Please note that this is a very basic example and you will likely encounter some problems when you delegate events to elements containing more than one level. When this happens, you will have to traverse the DOM tree upwards to find the containing element.


//The simplest way to do this might be to append a query parameter to your links:

<ul>
 <li><a href="Line 1">Line 1</a></li>
 <li><a href="Line 2">Line 2</a></li>
 <li><a href="Line 3">Line 3</a></li>
</ul>

You can use event.target for this:

Did not seem to be working so I made small change seems to be working now.

var ul = document.getElementById('test');
ul.onclick = function(event) {
    var target = event.target;
    alert(event.target.innerHTML);
};