Jitender
Jitender

Reputation: 7969

How to get index of match element using jquery

I want to get indexing of match element only. Like I have '.get' class in few TR. I want to get indexing based on '.get' class for instance. fiddle

.get 0
.get 1
.get 2


<table>
    <tr class="get"><td>view</td></tr>   
    <tr><td>view</td></tr>   
    <tr class="get"><td>view</td></tr>   
    <tr><td>view</td></tr>   
    <tr><td>view</td></tr>   
    <tr><td>view</td></tr>   
    <tr class="get"><td>view</td></tr>   
</table>

$('tr.get').click(function(){
    alert($(this,'.get').index())
})

Upvotes: 1

Views: 1880

Answers (3)

Seb D.
Seb D.

Reputation: 5205

Alternatively, you can directly attach the index in the handler. It will fail if you have dynamic data, but it will be much faster if you have a lot of data since it does not recompute the index each time.

$('.get').each(function(index) {
    $(this).click(function() {
        alert(index);
    })
})

DEMO

Upvotes: 1

abc123
abc123

Reputation: 18853

jsFiddle

JS

$('.get').click(function () {
    alert($(this, '.get').index())
})

HTML

<table>
    <tr class="get">
        <td>view</td>
    </tr>
    <tr>
        <td>view</td>
    </tr>
    <tr class="get">
        <td>view</td>
    </tr>
    <tr>
        <td>view</td>
    </tr>
    <tr>
        <td>view</td>
    </tr>
    <tr>
        <td>view</td>
    </tr>
    <tr class="get">
        <td>view</td>
    </tr>
</table>

Upvotes: 0

Satpal
Satpal

Reputation: 133453

.index( element )

If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector.

Use

$('.get').index(this);

DEMO

Upvotes: 3

Related Questions