Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: what is the n of clicked element

Tags:

jquery

So, in jQuery I can find the total number of a type of element with .find('selector').length, but how do I find out what n of the total the element is?

ie: How can I get back the information (n) that I've clicked on the first or second (or nth) button?

eg:

<table class="table-edit-components">
    <tr>
        <td>
            <div class="resource-links">
                ...
            </div>
            <button type="button" class="add-resource-link"></button>
        </td>
        <td>
            <div class="resource-links">
                ...
            </div>
            <button type="button" class="add-resource-link"></button>
        </td>
    </tr>
</table>
like image 849
Sanfly Avatar asked Mar 07 '23 14:03

Sanfly


1 Answers

You can use index() to get find out what element number you clicked on

$( ".add-resource-link" ).index( this );

demo

$(".add-resource-link").click(function(){
var index = $( ".add-resource-link" ).index( this );
  
  console.log(index)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-edit-components">
    <tr>
        <td>
            <div class="resource-links">
                ...
            </div>
            <button type="button" class="add-resource-link">click</button>
        </td>
        <td>
            <div class="resource-links">
                ...
            </div>
            <button type="button" class="add-resource-link">click</button>
        </td>
    </tr>
</table>
like image 197
Carsten Løvbo Andersen Avatar answered Apr 10 '23 05:04

Carsten Løvbo Andersen