I have an unordered list, with a couple list-items inside. Inside each of those is a link. What I want to do is find the position of the list-item when someone clicks the link inside it.
For example, if someone clicks the link inside the 3rd list-item, it gives me a value of 3.
I already have the click part, just need to figure out how to get the position of the list-item
Javascript only
Here’s a simple live example that does what you want (except the list does not have links)
http://jsfiddle.net/8k926/2/
In the “Result” box click on one of the list items. It will have a handler that pops up its sequence number.
The Javascript code is the following
Although
elsis array-like, it does not have aforEachmethod. We get around that by using theArray.prototype.forEachmethod.Update: Here’s a second live example that narrows things down to a specific list, as opposed to all list items.
http://jsfiddle.net/8k926/3/
Also, as a commenter points out,
forEachis not universally supported, but it is used here to simplify the code.