Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable instance get HTML element ID

Context:

I am playing with multiple DataTables at the same time (same page). I keep as global variables the DataTables object, e.g.

window.table_one = $('#mytableOne').DataTable( options );
[...]
window.table_two = $('#theirTableTwo').DataTable( options2 );

Problem:

As much as I could find on https://datatables.net and stackoverflow, the DataTables does not allow to get to the id of the HTML element table upon which DataTables is invoked.

Attempt:

Fortunately, we can use jQuery from the DataTables object, hence grab the id:

window.table_one.$('tr').closest('table').attr('id')

But calling jQuery like this feels like mashing strawberries with a tank, do you have lighter way to do so?

My other thought is to keep the DataTables instance in a global 'array', along with the html id. e.g.

window.tables = {
    'mytableOne': $('#mytableOne').DataTable( options )
}
[...]
window.tables[ '#theirTableTwo' ].DataTable( options2 )

Which looks lighter but uglier.

What are the good practices? I know that global vars should be feared, but I am kind of stuck with it (maintain old website).

like image 595
nicolallias Avatar asked Feb 17 '26 18:02

nicolallias


1 Answers

If you already have the dataTable instance you can try this:

myDataTable.context[0].sTableId
like image 81
maxence51 Avatar answered Feb 20 '26 10:02

maxence51



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!