Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  2] [ 5]  / answers: 1 / hits: 104066  / 14 Years ago, fri, february 25, 2011, 12:00:00

As a relative beginner with JS, I am struggling to try and find a solution to this.



I need to find out which line of an unordered list was clicked



<ul onclick=alert(this.clicked.line.id);>
<li id=l1>Line 1</li>
<li id=l2>Line 2</li>
<li id=l3>Line 3</li>
</ul>


I don't really want to add a onclick event to each individual line, I'm sure there must be a way ??


More From » html

 Answers
27

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.


[#93581] Wednesday, February 23, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;