Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to get the index of an element in the selection array?

I have an HTML structure like this:

<div class="container">
  <div class="item">
    <a href="#">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
  </div>
  <div class="item">
    <a href="#">4</a>
    <a href="#">5</a>
    <a href="#">6</a>
  </div>
</div>

I select all the A-s with jQuery, and get a total of 6 objects here. I want to get the index of the A in the array of 6 (so I can detect which A has been clicked, for example), but when I use .index() I get the index of the element relative to its parent. So for the 5th A I get the same index as for the 2nd, because te 5th is actually the second in its group within its div.item:

$('a').click(function(){
    console.log ( $(this).index() ); // returns "1" for the 5th A
});

So is there a way to get the index of the clicked element within the array of the selection, instead of within the parent in the DOM?

like image 203
vladko13 Avatar asked Mar 09 '15 21:03

vladko13


People also ask

How do you find the index of an object in an array?

JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.

How do you get the index of an object inside an array that matches the condition in jQuery?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you select an element by index?

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

What is slice () method in jQuery?

slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.


1 Answers

You can pass the clicked element to the index method:

var $a = $('.container > .item > a').click(function() {
    console.log ( $a.index(this) ); 
});
like image 199
undefined Avatar answered Oct 10 '22 09:10

undefined