Search code examples
javascriptjquerydatatables

How to check if variable is an initialized DataTable?


Is there a way to determine if a variable is an initialized DataTable or not? I'm basically trying to do this:

if (isDataTable(variable)) {
    // datatable ... do datatable stuff
} else {
    // not a datatable... do other stuff
}

I assumed $.fn.dataTable.isDataTable() could be used, but this only works for table selectors, not for variables containing an initialized DataTable. This function is returning false for such variables (EDIT: the creator of DataTables has since extended $.fn.dataTable.isDataTable() in this commit so that this is no longer true):

var table = $("#table").DataTable(); // Valid initialized DataTable
console.log($.fn.dataTable.isDataTable("#table")); // Returns true
console.log($.fn.dataTable.isDataTable(table)); // Returns false...why?

Solution

  • I asked this question to the creator of DataTables, and he suggested using instanceof:

    if (table instanceof $.fn.dataTable.Api) {
        // variable "table" is a valid initialized DataTable ... do datatable stuff
    } else {
        // variable "table" is not a datatable... do other stuff
    }
    

    This approach works exactly as needed. He also went on to extend $.fn.dataTable.isDataTable() in this commit so that it will allow variable inputs.