3

I have such table

<table id="myTable">
<tbody>
<tr>
    <td class="class1">aaa</td>
    <td class="class1">bbb</td>
    <td class="class1">ccc</td>

    <td class="class2">ddd</td>
    <td class="class2">eee</td>
</tr>

<tr>
    <td class="class1">fff</td>
    <td class="class1">ggg</td>
    <td class="class1">hhh</td>

    <td class="class2">iii</td>
    <td class="class2">jjj</td>
</tr>
</tbody>
</table>

I want to give class name, and get the columns' indices, which has that class name.
For example I give "class 2" and get 3 and 4.
I tried this. But index gives me the last column's index number.

 var indices = $("#myTable tbody tr").first().children("td.class2").index();

I need an array that includes all index values.

2 Answers 2

4

Use .each().

var indices = [];
$("#myTable tbody tr").first().children("td.class2").each(function(){
    indices.push($(this).index());
});
// indices = [3, 4]

In modern web browsers you can use Array#map.

var indices = $("#myTable tbody tr").first().children("td.class2").get().map(function(self){
    return $(self).index();
});
2
  • There is no real need in using Array.map when jQuery has good cross-browser solution.
    – VisioN
    Jan 13, 2013 at 20:56
  • @VisioN, disagree. There is a need to know that these functions are available natively
    – Alexander
    Jan 13, 2013 at 21:01
4

You can use map() and index() methods:

var indices = $("#myTable tr:first td.class2").map(function(i) {
    return $(this).index();
}).get();

console.log(indices); // [3, 4]
3
  • Being pedantic, .map() should return a jQuery object
    – Alexander
    Jan 13, 2013 at 20:59
  • @Alexander while get() returns native JS array out of it.
    – VisioN
    Jan 13, 2013 at 21:02
  • @VisioN, I know. But, my statement is still valid
    – Alexander
    Jan 13, 2013 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.