Neil
Neil

Reputation: 3291

Jquery delete elements that were created using .after

I have a table in my html file which has the column header hard-coded:

<table id="debugger-table">
    <tr>
        <th>Attribute</th>
        <th>Computed</th>
        <th>Correct</th>
    </tr>
</table>

Which I populate with values for row 2 onwards in a .js file using jquery:

tableString = '';

DEBUG_DATA.forEach(function(debug_line){
    tableString += '<tr><td>' + debug_line['attribute'] + '</td><td>' + debug_line['computed'] + '</td><td>' + debug_line['correct'] + '</td>'
});

$('#debugger-table tr:last').after(tableString);

When the user performs a certain action I want to update the values. My question is how do I remove the text I've added, so that I can replace it with new text, instead of just appending the new values after the old ones.

I figure I could destroy the whole table and then create a new one with the column headers. Seems overkill though. Is there a way to refer back to the text added with .after, and delete it? thanks.

Upvotes: 0

Views: 32

Answers (1)

Son Nguyen
Son Nguyen

Reputation: 1482

Store the addition into a jQuery object:

const rows = $(tableString);
('#debugger-table').append(rows); // Tip: this is better than
                                  // $('#debugger-table tr:last').after(rows);

Then later remove it when needed:

rows.remove();

Upvotes: 3

Related Questions