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_a'>text1</span>
<span class='spantype2_b'>text2</span>
<span class='spantype1_c'>text3</span>
So if I click on text3 I want to return 1 not 2.
This answer from here doesn't work because each span has a unique class so 0 is returned, see the jsfiddle here:
$( "span" ).click(function() {
var index = $('.' + $(this).attr('class')).index($(this));
alert(index);
});
Also, the below code returns -1, see the example jsfiddle here:
$( "span" ).click(function() {
var aclass = $(this).attr('class');
var back = aclass.lastIndexOf("_");
var classtosearch = aclass.substring(0, back);
alert($('.' + 'span[class^="' + classtosearch + '"]').index($(this)));
}