Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of clicked element in collection with jQuery

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).

like image 825
thom Avatar asked Apr 04 '11 22:04

thom


People also ask

How do I get the index of a clicked 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);

How to get the index of an element in jQuery?

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.

How do I know which DIV is clicked?

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.

What is EQ jQuery?

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).


1 Answers

This will alert the index of the clicked selector (starting with 0 for the first):

$('selector').click(function(){     alert( $('selector').index(this) ); }); 
like image 133
Ant Avatar answered Oct 06 '22 14:10

Ant