dnns dnns - 6 months ago 9
jQuery Question

Javascript / jQuery use old DOM object in callback

I retrieve a table with the following script:

$("#table").load("index #table", function(tableNew) { // code });


Before I do this, I like to store the old table in a variable. When retrieving the new table, I want to compare it with the old table.

var tableCurrent = document.getElementById('table');
console.log(tableCurrent); // object

$("#table").load("index #table", function(tableNew) {
var htmlNew = $.parseHTML(tableNew);
var rowsNew = htmlNew[0].getElementsByTagName('tr');

console.log(tableCurrent); // null

// compare new with old

// insert new table in DOM
});


How can I 'access' the old table inside the 'load' callback? I know the old table will be removed which is correct.

Answer

EDIT: Store as jquery object to avoid hitting the old reference as the new jQuery object is not a reference to the old table DOM element

var tableCurrent = document.getElementById('table');
console.log(tableCurrent); // object
var $tableCurrent = $('table');

$("#table").load("index #table", function(tableNew) {
   var htmlNew = $.parseHTML(tableNew);
   var rowsNew = htmlNew[0].getElementsByTagName('tr');

   console.log($tableCurrent); // this should be the jquery table object
   console.log($tableCurrent[0]); // actual table element

   // compare new with old

   // insert new table in DOM
});