JoshWeinstein JoshWeinstein - 1 year ago 75
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:

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 Source

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

   var thisChangeIndex = $('.change').index(this);
<script src=""></script>
  <span class="change">change1</span>
  <span class="change">change2</span>
  <span class="change">change3</span>
  <span class="change">change4</span>
  <span class="change">change5</span>
  <span class="change">change6</span>
  <span class="change">change7</span>
  <span class="change">change8</span>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download