Reputation: 1030
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.
Upvotes: 2
Views: 188
Reputation: 15393
Try,
$( "span" ).click(function() {
var index = $('.' + $(this).attr('class')).index($(this));
alert(index + 1);
});
Upvotes: 2
Reputation: 85545
Try this:
var index = $(this).parent().find($(this)).index();
Upvotes: 0