JoshWeinstein JoshWeinstein - 5 months ago 9
jQuery Question

Find the index of an element in an array created by toArray in JS/JQuery

I have a bunch of spans of class = "change" and each has a unique id. I created an array of those spans using:

var changesArray = $('.change').toArray()


I want to be able to get the index of the span in the array when I click on it. I tried:

$('.change').click(function(){
var thisChange = $(this).attr('id');
var thisChangeIndex = $.inArray(thisChange,changesArray);
});


But all I get is -1 for every .change I click on.

I'm a bit of a newbie with this type of code. Help?

Answer

The toArray method says

Retrieve all the elements contained in the jQuery set, as an array.

You are looking for a particular id in the array - that will never work.

If you want the index of the item you can use .index()

 $('.change').click(function(){
   var thisChangeIndex = $('.change').index(this);
   console.log(thisChangeIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span class="change">change1</span>
  <span class="change">change2</span>
  <span class="change">change3</span>
  <span class="change">change4</span>
 </div>
<div>
  <span class="change">change5</span>
  <span class="change">change6</span>
  <span class="change">change7</span>
  <span class="change">change8</span>
 </div>