Adding dataTable to HTML table with JavaScript: Cannot read property 'parentNode' of null

webminer07 picture webminer07 · May 15, 2015 · Viewed 13.1k times · Source

I am trying to make the table that I am creating on the fly with JavaScript into a .dataTable. I have compared my code to my co-workers and it is almost identical. I have made the necessary changes, but I keep getting the JavaScript error: "Cannot read property 'parentNode' of null" in the console.

All of the code is executing perfectly. The new table is being displayed in the browser, but once it tries to run the line $('#data').dataTable({"paging": false}); it gives me the error.

Can anyone see what is causing this? Maybe a scope error, or a parentheses/bracket in wrong spot.

function Load(p1, p2) {

var work= "";

$('#div1').empty();

var tablearea = document.getElementById('div1'),
table = document.createElement('table');
table.id = "data";
table.style.fontSize = "small";
table.width = "100%";

var tbody = document.createElement('tbody');
tbody.id = "dataTB";
table.appendChild(tbody);
tablearea.appendChild(table);

var url = sessionStorage.baseUrl + "XXXXXXXXX";

$.getJSON(url)
    .done(function (data) {

        var results = $.parseJSON(data);

        if (results != null)
        {
            for (i = 0; i < results.length; i++) {
                    work += "<tr><td>" + results.data[i].info + "</td></tr>";
                }
        }

        $('#dataTB').html(work);

        $('#data').dataTable({"paging": false});
    })
    .fail(function (jqXHR, textStatus, err) {
        alert('Error: ' + err);
});
}

Answer

Alon Eitan picture Alon Eitan · May 15, 2015

I think you must include a valid thead element in your table