Steve
Steve

Reputation: 602

How to get the (DOM/document) index of a clicked element in JQuery

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!

Upvotes: 1

Views: 1925

Answers (3)

Alnitak
Alnitak

Reputation: 339816

This works, although it probably isn't very efficient:

$(document).on('click', '*', function (e) {
   e.stopPropagation();
   var others = document.getElementsByTagName(this.tagName);
   var index = [].indexOf.call(others, this);
});

Upvotes: 4

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

Using Alnitak solution, this will work for any element.

function getElementIndex(DOMELEMENT)
{
   var elements = document.getElementsByTagName(DOMELEMENT.tagName);
   return index = [].indexOf.call(elements , DOMELEMENT);
}

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Use

$(document).on('click','*',function (e) {
    e.stopPropagation();
    var tag = this.tagName;
    var index = $(tag).index(this);  // it now works

    $('#output').html(index);
});  

Demo at http://jsfiddle.net/6n5zp/1/

Upvotes: 4

Related Questions