javascriptjquerydatatablesdatatables-1.10

Can't destroy() jQuery Data Table


I am having an issue with trying to destroy a JQuery Data Table.

Here is where I initialize it:

$(document).ready(function() {
    var table = $(".dynamic-wide-table").DataTable({
        "aaSorting": [],
        "scrollX": true,
        "scrollY": 530,
        "scrollCollapse": true,
        "lengthMenu": [
            [100, 400, 1000, 5000, -1],
            [100, 400, 1000, 5000, "All"]
        ],
        "retrieve": true
    });
});

Here is where I try to destroy it:

$(document).ready(function() {  // Note that my page has two tables on it!
    table.destroy();
    table[0].destroy();
});        // Trying to delete both tables first, then just the first table

Here are my errors:

Uncaught TypeError: table.destroy is not a function
Uncaught TypeError: table[0].destroy is not a function

Does anybody know what's going on?! I'm very confused.

Edit:

Here is an image of what happens when I console.log table.

enter image description here


Solution

  • Instantiate the tables with an each() loop and store them in an array:

    $(document).ready(function() {
            var tables = [];
    
        $("table").each(function(i){
         var table = $(this).DataTable({
            "aaSorting": [],
            "scrollX": true,
            "scrollY": 530,
            "scrollCollapse": true,
            "lengthMenu": [
                [100, 400, 1000, 5000, -1],
                [100, 400, 1000, 5000, "All"]
            ],
            "retrieve": true
        });
        tables.push(table);
        });
    
        $('#button').click( function () {
            // Then you can call destroy on that object
            var elem = tables[0].table().node();
            tables[0].destroy();
            // And empty the element
            $(elem).empty()
        } );
    } );
    

    Link to jsFiddle