Chris Evans Chris Evans - 1 year ago 66
jQuery Question

Remove <tr>s that I appended to a <tbody>

I'm creating a page that basically saves website bookmarks. It's very basic, but what I'm trying to achieve is this:

On page load it calls a function called

. The function sends an ajax request backend and retrieves a json_encoded array of websites, with url & title.

When I call the
function, at the start of it I want to remove any previously appended
s from the
but nothing I have tried has actually worked and I am lost. I've spent the last 20 minutes or so browsing SO and google for an answer and none of the solutions have worked for me.

The idea, ultimately, is for me to be able to call this function more than once, and it'd just overwrite the table's contents each time.

Here is my code:


<table class="table table-striped" id="pagesTable">
<th class="col-sm-10">Page Name</th>
<th class="col-sm-2"></th>



function loadPages(){

// Code to remove the previously appended <tr>s from the <tbody> should be here

url: "index.php?page=getAllPages",
type: "GET",
dataType: "json",
success: function(ret){
$.each(ret, function(){
$('#pagesTable > tbody').append(
'<tr><td class="col-sm-10"><a href="' + this.url + '">' + this.title + '</a></td>'
+ '<td class="col-sm-2"><button class="btn btn-danger" data-type="remove" data-id="' + + '">Remove</button></td></tr>'

Things I have tried

$("#pagesTable > tbody").children().remove();

$("#pagesTable > tbody tr").remove();

$("#pagesTable > tbody").empty();

$("#pagesTable > tbody").html("");

Assigning classes to the
s, and executing
on the class name like so:

I appreciate any help, thanks.

Answer Source

Inside the success block of your ajax query use the following code before appending:

$("#pagesTable tbody tr").remove();

Don't forget to upvote if you find this helpful!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download