Find the index of the element that was clicked with jQuery

Posted in Javascript -

There may be times when you need to know the index of the element that is clicked from within a group of elements e.g. a group of divs inside another div. This can be done easily with jQuery using the index() function.

Example HTML

The following HTML has a containing <div> with the id "example" and this has several <div>s inside it. The index returned by jQuery is zero based so I've put text into the <div>s noting the index starting from 0. The final div outside #example is a placeholder for displaying index of the div that is clicked.

<div id="example">
    <div>div index 0</div>
    <div>div index 1</div>
    <div>div index 2</div>
    <div>div index 3</div>
    <div>div index 4</div>
</div>
<div id="example_index">Click one of the above divs</div>

Example jQuery for versions 1.3.2 and earlier

The following jQuery assigns a click handler to all divs within the #example div. When they are clicked the index is looked up and then written into the #example_index placeholder.

$(document).ready(function() {

    $("#example div").click(function() {
        var index = $("#example div").index(this);
        $("#example_index").html("Index " + index + " was clicked");
    });
   
});

Example jQuery for versions 1.4.0 and later

The above code will also work for later versions of jQuery, but it can be done more concisely as pointed out by Antony in the comments below:

$(document).ready(function() {

    $("#example div").click(function() {
        var index = $(this).index();
        $("#example_index").html("Index " + index + " was clicked");
    });
   
});

Example in action

Here's the above example working. If you are viewing this post in a feed reader then you will need to click through to view it a web browser to be able to see the example working.

div index 0
div index 1
div index 2
div index 3
div index 4
Click one of the above divs

No matches

If there are no matches for $("selector here").index(this); then -1 is returned.



Related posts:


Comments