Datatables. How to loop through all rows and get id of each tr entry
13,437
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()
Related videos on Youtube
Author by
Infinity
Updated on June 04, 2022Comments
-
Infinity almost 2 years
This questions targets to
Datatables
plug-in forJQuery
.I need to loop through all table rows (even paginated) and get
id
of eachtr
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 usingsubstr
).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
oftr
(with this sample dataetc_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
. -
Infinity about 6 yearsThanks for an answer, but I get an error:
row.data is not a function
-
spawnedc about 6 yearsSorry, I missed that part. I updated the answer. Basically, the
row
object doesn't work as I expected. You can dotbl.row(index).data()
instead to get the data. -
Infinity about 6 yearsYea, I've figured it out by adding inside loop
var row = tbl.row();
, but in this case I got printed info only about 1 row. I've tried to use your updated answer - the same, only 1 log printed to console. Also as I think thererow(index)
should be added invar id
too, alsovalue
should be removed from console log. But main problem that this not loop through all rows, only first one. -
spawnedc about 6 yearsUpdated the answer. Basically, there's
rows().every()
method, which allows you to loop through every row and you can access the row object usingthis
. -
Infinity about 6 yearsThank your code before editing helped me, I achieved it without
every
. -
Infinity about 6 yearsI have another question related to this one, maybe you could assist me? stackoverflow.com/questions/49151693/…
-
spawnedc about 6 yearsI added my answer to that one.