nicolallias
nicolallias

Reputation: 1122

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).

Upvotes: 3

Views: 5110

Answers (2)

maxence51
maxence51

Reputation: 1054

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

myDataTable.context[0].sTableId

Upvotes: 4

davidkonrad
davidkonrad

Reputation: 85528

You could use $.fn.dataTable.tables(). This return a vanilla NodeList of all table elements that has been initialised as a DataTable. For example, in your case

console.log( $.fn.dataTable.tables()[0].id );

would return mytableOne. So iterate over that NodeList and you can get all id's (or DOM nodes). A perfect replacement for your global array. That could also be useful for example if your table id is dynamically created with a timestamp or unique random number you not know upfront.

You can work with the API on an unknown table id like this :

var temp = $('#'+$.fn.dataTable.tables()[0].id).DataTable();
temp.row.add(['a','b','c']).draw();

Upvotes: 3

Related Questions