1

Hi I have a series of tags with multiple 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 party'>text1</span>
<span class='spantype2 party'>text2</span>
<span class='spantype1 party'>text3</span>

So if I click on text3 I want to return 1 not 2. If I click on text1 I want to return 0. And of course if I click on text2 I want to return 0.

This answer from here doesn't work because index is always returned as -1 (because there are multiple classes), see my example jsfiddle:

$( "span" ).click(function() {
    var index = $('.' + $(this).attr('class')).index($(this));
    alert(index);
});
Community
  • 1
  • 1
user2104778
  • 992
  • 1
  • 14
  • 38

1 Answers1

1

I'd use a filter to grab the class you're interested in, and search based on that:

$("span").click(function() {
    var spanType = $.grep(this.classList, function (className) {
        return /^spantype/.test(className);
    })[0];

    var index = $('.' + spanType).index($(this));
    alert(index);
});

I used classList above, but for better support (see caniuse.com), you could probably use className instead:

$("span").click(function() {
    var spanType = $.grep(this.className.split(/\s+/), function (className) {
        return /^spantype/.test(className);
    })[0];

    var index = $('.' + spanType).index($(this));
    alert(index);
});
cmbuckley
  • 40,217
  • 9
  • 77
  • 91