Infinity
Infinity

Reputation: 898

Datatables. How to loop through all rows and get id of each tr entry

This questions targets to Datatables plug-in for JQuery.

I need to loop through all table rows (even paginated) and get id of each tr element.

HTML table like this:

<table>
  <thead>
    <tr>
      <th>Header content 1</th>
      <th>Header content 2</th>
    </tr>
  </thead>
  <tbody>
    <tr id="etc_1_en">
      <td>Etc 1</td>
      <td>Etc 2</td>
    </tr>
    <tr id="etc_1_ru">
      <td>Etc 3</td>
      <td>Etc 4</td>
    </tr>   
    <tr id="etc_1_fr">
      <td>Etc 5</td>
      <td>Etc 6</td>
    </tr>   
    <tr id="etc_2_en">
      <td>Foo 1</td>
      <td>Foo 2</td>
    </tr>
    <tr id="etc_2_ru">
      <td>Foo 3</td>
      <td>Foo 4</td>
    </tr>   
    <tr id="etc_2_fr">
      <td>Foo 5</td>
      <td>Foo 6</td>
    </tr>       
  </tbody>
</table>

So I need to loop through each row and hide row if last 2 characters is not equal to en (with this checking everything fine, I'm using substr).

I can loop through all rows in following:

tbl = $('#myTable').DataTable();
var data = tbl.rows().data();

data.each(function (value, index) {
    console.log('Data in index: ' + index + ' is: ' + value);
});

But I can't find a way to get id of tr (with this sample data etc_1_en, etc_1_ru and so on). Could someone help me?

I've tried to pass in function id as parameter, but it returns - undefined.

Upvotes: 2

Views: 18173

Answers (1)

spawnedc
spawnedc

Reputation: 476

You can loop through the rows() using rows().every(). This way you will have access to the row object, which will give you both data and id.

tbl = $('#myTable').DataTable();

tbl.rows().every(function () {
  var data = this.data();
  var id = this.id();
  console.log('Data in id: ' + id + ' index: ' + index + ' is: ' + data);
});

More info: https://datatables.net/reference/api/rows().every()

Upvotes: 5

Related Questions