Chris Evans Chris Evans - 4 months ago 10
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

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

When I call the
loadPages()
function, at the start of it I want to remove any previously appended
<tr>
s from the
<tbody>
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:

HTML

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

</tbody>
</table>


Jquery

function loadPages(){

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

$.ajax({
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="' + this.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
tbody
and
tr
s, and executing
.remove()
on the class name like so:
$(".class").remove();


I appreciate any help, thanks.

Answer

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!!

Comments