Getting the Index of an Item in a Selection - J Query

When binding an event for a wide range of selected elements on a page, you need to know exactly which item was clicked from the selected set to “personalize” the action of the bound event.


When we click an item, we can use the core method index() to search through a selection to see what index the item is at:


Figure : shows the output

We start by binding all <div>elements to a click event. Then when a <div>is clicked, we can figure out which <div>was clicked by searching for the item in the same selection: $("div").index(this);, where this is the <div>that was clicked.

The core method index() allows you to get the index of the DOM element you are looking for from a jQuery set. As of jQuery 1.2.6, you can also pass in the index of a jQuery collection to search for. The method will return the index of the first occurrence it finds:

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics