trante
trante

Reputation: 34006

JQuery get indeces of multiple columns regarding to class name

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.

Upvotes: 3

Views: 633

Answers (2)

VisioN
VisioN

Reputation: 145408

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]

Upvotes: 4

Alexander
Alexander

Reputation: 23537

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

Upvotes: 4

Related Questions