Find the index of the element that was clicked with jQueryFind the index of the element that was clicked with jQuery

Posted May 19th, 2009 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 Javascript

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 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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus