1

I'm working with a legacy jQuery project and need to get the indices of all columns of a table that have the class unsorted. jQuery can easily get a single index, but I need to get an array of indices. How can I do this?

For example, this will return a single integer even though there are multiple columns with the unsorted class:

$('.some-table th').index($('th.unsorted'))

Other Questions

Although this question mentions jQuery, it is really has nothing to do with jQuery or DOM elements, and therefore doesn't help me.

iconoclast
  • 21,213
  • 15
  • 102
  • 138

2 Answers2

1

Since jQuery does not has that function, it could be

const $ths = $('.some-table th');
let indices = $.map($('th.unsorted'), function(element) {
  return $ths.index(element);
});

Or you could extend the function by yourself.

jQuery.fn.extend({
  indices: function(selector) {
    return $.map($(selector), function(element) {
      return this.index(element);
    });
  },
});

let indices = $('.some-table th').indices('th.unsorted');

Moreover, you could write the search logic by yourself for the performance reason.

Epic Chen
  • 1,282
  • 12
  • 17
0

If all of your th.unsorted are siblings (all in the same thead) then you don't need collection.index(selector) and can apply .map() to the th.unsorted list directly.

If they're (eg) on different rows, then use the collection.index(element) from the other answer.

console.log($("table th.unsorted").map((i, e) => $(e).index()).toArray())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <th>1</th>
    <th class='unsorted'>2</th>
    <th class='unsorted'>3</th>
    <th>4</th>
    <th class='unsorted'>5</th>
  </thead>
</table>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57