How do I get the index of clicked item in the code below?
$('selector').click(function (event) { // get index in collection of the clicked item ... });
With Firebug I saw this: jQuery151017197709735298827: 2
(I've clicked in the second element).
index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements. Pass the selector to the index(selector) . $(this). index(selector);
The index() method returns the index position of specified elements relative to other specified elements. The elements can be specified by jQuery selectors, or a DOM element. Note: If the element is not found, index() will return -1.
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.
jQuery :eq() Selector The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).
This will alert the index of the clicked selector (starting with 0 for the first):
$('selector').click(function(){ alert( $('selector').index(this) ); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With