简体   繁体   中英

Finding Dom Node Index for elements of a certain class of a multi-class element

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);
});

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM