How to clear a table before inserting rows in it?

April 23, 2018, at 05:34 AM

Before you keep reading, keep in mind I have done my research and I still cant find a solution. So I've got a table that I am populating with JQuery and it populates it properly but I can't seem to be able to clear it before populating it again. Here is my HTML:

$("#searchBut").click(function() { 
  $('tbody > tr').remove(); 
  var searchT = $('#searchField').val(); 
  var results = $('#logs'); 
  results.innerHTML = 'test'; 
  console.log("results" + results); 
  $.post('includes/searchProj.php', { 
    projName: searchT 
  }, function(data) { 
    var data2 = JSON.parse(data); 
    $.each(data2, function(key, val) { 
      pArray.push("<tr><td> " + + "</td>" + "<td>" + + "</td>" + "<td>" + val.note + "</td>" + "<td>" + "</td>" + " </tr>"); 
    $("<tbody>", { 
      "class": "tbody", 
      html: pArray.join("") 
<script src=""></script> 
<table id="table" style="width:50%"> 
      <th>Project Name</th> 
      <th>Date Created</th> 
      <th>Total Time for Project</th> 
  <tbody class="tbody"> 

I have also tried $('tbody > tr').clear() and $('tbody > tr').html(""); and played around with selecting it with tbody or table and a couple other variations.

Nothing seems to clear the table. Any help would be appreciated.

Answer 1


Since what you are wanting to do is remove DOM elements with the tag tbody that are children of the table element with id table, you can:

  1. find each element
  2. remove the element from the parent


  1. find each element:
    • var body_elements = document.querySelectorAll('#table tbody')
      • see CSS query selectors for syntax of what parameters to pass to the querySelectorAll method
  2. remove each element from parent (removing each element from the page)
    • body_elements.forEach((element)=>{ element.parentNode.removeChild(element)});

all together

var body_elements = document.querySelectorAll('#table .tbody')
how to Send 2 values of form by Ajax with POST method

how to Send 2 values of form by Ajax with POST method

how to Send 2 values of form ( A & B )to checkphp by Ajax with POST method

count characters textarea and change color counted

count characters textarea and change color counted

I have the simple code, it's works fineThis code counting characters in textarea and result show in div 0,1,2 etc

Submitting form within a function

Submitting form within a function

Probably a very easy fix for you JS gurus out there, currently I have a form with some basic validationIf i call it outside of a submit function it works fine, however i need the form to submit once it checks the validation, can anyone help? Also is the correct...