2

Hi I have a series of tags with different classes. When a span is clicked I want to return the index of the class of spans. So not the index of the spans themselves.

Here is a sample html:

<span class='spantype1'>text1</span>
<span class='spantype2'>text2</span>
<span class='spantype1'>text3</span>

So if I click on text3 I want to return 1 not 2.

This answer from here doesn't work:

$( "span" ).click(function() {
    var index = $(this).parent().children().index(this);
alert(index);
});

EDIT: What I meant was if I click on text3 I return 1, and if I click on text1 I return 0. My apologies. And of course if I click on text2 I return 0.

Community
  • 1
  • 1
user2104778
  • 992
  • 1
  • 14
  • 38

2 Answers2

2

Try,

$( "span" ).click(function() {
    var index = $('.' + $(this).attr('class')).index($(this));
    alert(index + 1);
});

DEMO

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
  • Beautiful. You answered my question when I didn't even write it properly. See edited question above. I tested your solution with more spans and it worked. See [here](http://jsfiddle.net/puLNt/3/). – user2104778 Apr 11 '14 at 13:28
  • Sudhar, I tried this with my actual html file and it returns -1 every time. I built a [JSFiddle](http://jsfiddle.net/puLNt/7/) with the same dom structure to show you. The problem is that there are two classes for each span but we only care about the index of the first one. So I don't know why I am getting -1. Any ideas? – user2104778 Apr 11 '14 at 13:47
0

Try this:

var index = $(this).parent().find($(this)).index();
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231