anmarti
anmarti

Reputation: 5143

Assign and retrieve an html table to a javascript variable with jQuery

I want to backup an html table to afterwards filter it using jquery:

$('.row').closest('td').not(':contains(' + v + ')').parent('tr').remove();

Since I do remove() I have to back up the rows before:

var allTable = $('#mytable').html();

And then, when filter is performed I turn back to previous table data:

$('#mytable').html($(allTable));

But this does not work. If I do:

alert($(allTable).filter('tr').length);

next to the first assignment, zero rows are returned.

Please, can you assist me?

Upvotes: 0

Views: 2970

Answers (3)

Andreas L.
Andreas L.

Reputation: 2923

Did you solve this problem?

I suggest a workaround.

Instead of using your cloned table, make a (temporary) copy of it and use it for alert.

var alertTable = allTable;
alert($(alertTable).filter('tr').length);

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337620

filter() is used to find elements within an array of elements. This isn't what you need. You're looking to find() the child elements within another. Also, storing the HTML only to turn it back in to a jQuery object is a little redundant - you may as well just store the jQuery object itself. Try this:

var $table = $('#mytable');
$table.remove(); // use your existing logic here
alert($table.find('tr').length);
$table.appendTo('body'); // add the table back in to the DOM when conditions are met

Example fiddle

Upvotes: 1

Andy Foster
Andy Foster

Reputation: 160

I ran into a similar issue when using a highlight function. I solved it by cloning the table into a hidden div and restoring it from there, instead of from a variable. see jquery highlight() breaking in dynamic table

Upvotes: 0

Related Questions