I want to get the index of a clicked element using jquery – this should be easy with .index() but I don’t want the index within a narrowly defined selector such as $('div').index().
What I want is the unique index of that element on the page/in the DOM – something like $(everything).index() if it existed.
Here’s my simple jquery click function:
$("div").click(function (e) {
e.stopPropagation();
index = $(this).index();
});
Which I’ve used with some sample HTML:
<div>DIV 0 - I want to show as index=0 (which I do)</div>
<div>DIV 1 - I want to show as index=1 (which I do)</div>
<span>SPAN 0 - I want to show as (span) index=0</span>
<div>DIV 2 - I want to show as index=2 (but I don't, I show as 3)
<div>DIV 3 - I want to show as index=3 (but I don't, I show as 0)</div>
<span>SPAN 1 - I want to show as (span) index=1</span>
<span>SPAN 2 - I want to show as (span) index=2</span>
</div>
I’ve JSfiddled about with it to play with.
My problems are these:
1) I don’t know how to get a unique index number for these DIVS (or any other element for that matter) as $(this) only refers to the CURRENT selection, so embedded DIVs re-index at zero, once clicked.
2) I need this to work for ANY/ALL html tags (not just DIVs)
Thanks for any help you could give!
Use
Demo at http://jsfiddle.net/6n5zp/1/