Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript delete a table tbody tag

I know I can use the following code to remove rows in vanilla Javascript:

var table = document.getElementById('table');
    
function deleteRow () {
  table.deleteRow(1);
};
table { background: #ccc; width: 100%; }
table thead { background: #333; color: #fff; }
table tbody { background: magenta; color: #fff; }
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
    <thead>
      <tr>
        <td>foo</td>
        <td>bar</td>
      </tr>
    </thead>
      <tbody>
        <tr>
          <td>lorem</td>
          <td>ipsum</td>
        </tr>
      </tbody>
      <tbody>
        <tr>
          <td>lorem</td>
          <td>ipsum</td>
        </tr>
      </tbody>
    </table>

But this code leaves an empty tbody tag behing. JS has methods for removing thead and tfoot elements, but it seems it's missing a deleteTbody one.

How am I supposed to remove a tbody and all it's contents by using pure javascript only? No jQuery, please!

like image 623
darksoulsong Avatar asked Jan 21 '16 20:01

darksoulsong


People also ask

Is Tbody a table tag?

The <tbody> tag is used to group the body content in an HTML table. The <tbody> element is used in conjunction with the <thead> and <tfoot> elements to specify each part of a table (body, header, footer). Browsers can use these elements to enable scrolling of the table body independently of the header and footer.

How do you clear a table in JavaScript?

This can be done by using JavaScript. First of all set the ID or unique class to the table. Select the table element and use remove() or detach() method to delete the all table rows.

Can a table have 2 Tbody tags?

You may use more than one <tbody> per table as long as they are all consecutive. This lets you divide the rows in large tables into sections, each of which may be separately formatted if so desired.

How do you delete a table in HTML?

The remove() method is used to remove the table row from an HTML table using JavaScript. remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements.


1 Answers

Try using:

var tbl = document.getElementById("table"); // Get the table
tbl.removeChild(tbl.getElementsByTagName("tbody")[0]); // Remove first instance of body

https://jsfiddle.net/Ltdr2qv4/1/

like image 61
MaVRoSCy Avatar answered Oct 04 '22 15:10

MaVRoSCy