简体   繁体   English

删除 HTML 表中的所有行

[英]Delete all rows in an HTML table

How can I delete all rows of an HTML table except the <th> 's using Javascript, and without looping through all the rows in the table?如何删除 HTML 表的所有行,除了<th>使用 Javascript 并且不循环遍历表中的所有行? I have a very huge table and I don't want to freeze the UI while I'm looping through the rows to delete them我有一个非常大的表,我不想在循环遍历行以删除它们时冻结 UI

这将删除所有行:

$("#table_of_items tr").remove(); 

Keep the <th> row in a <thead> and the other rows in a <tbody> then replace the <tbody> with a new, empty one.<th>行保留在<thead>中,将其他行保留在<tbody>中,然后将<tbody>替换为新的空行。

ie IE

var new_tbody = document.createElement('tbody');
populate_with_new_rows(new_tbody);
old_tbody.parentNode.replaceChild(new_tbody, old_tbody)

Very crude, but this also works:非常粗糙,但这也有效:

var Table = document.getElementById("mytable");
Table.innerHTML = "";

Points to note, on the Watch out for common mistakes :注意点,注意常见错误

If your start index is 0 (or some index from begin), then, the correct code is:如果您的起始索引为 0(或从开始的某个索引),那么正确的代码是:

var tableHeaderRowCount = 1;
var table = document.getElementById('WRITE_YOUR_HTML_TABLE_NAME_HERE');
var rowCount = table.rows.length;
for (var i = tableHeaderRowCount; i < rowCount; i++) {
    table.deleteRow(tableHeaderRowCount);
}

NOTES笔记

1. the argument for deleteRow is fixed 1. deleteRow 的参数是固定的
this is required since as we delete a row, the number of rows decrease.这是必需的,因为当我们删除一行时,行数会减少。
ie; IE; by the time i reaches (rows.length - 1), or even before that row is already deleted, so you will have some error/exception (or a silent one).当我到达(rows.length - 1)时,或者甚至在该行已经被删除之前,所以你会有一些错误/异常(或无声的)。

2. the rowCount is taken before the for loop starts since as we delete the "table.rows.length" will keep on changing, so again you have some issue, that only odd or even rows only gets deleted. 2. rowCount 是在 for 循环开始之前获取的,因为当我们删除“table.rows.length”时,“table.rows.length”会不断变化,所以你又遇到了一些问题,只有奇数行或偶数行才会被删除。

Hope that helps.希望有帮助。

This is an old question, however I recently had a similar issue.这是一个老问题,但是我最近遇到了类似的问题。
I wrote this code to solve it:我写了这段代码来解决它:

var elmtTable = document.getElementById('TABLE_ID_HERE');
var tableRows = elmtTable.getElementsByTagName('tr');
var rowCount = tableRows.length;

for (var x=rowCount-1; x>0; x--) {
   elmtTable.removeChild(tableRows[x]);
}

That will remove all rows, except the first.这将删除所有行,除了第一行。

Cheers!干杯!

Assuming you have just one table so you can reference it with just the type.假设您只有一个表,因此您可以仅使用类型来引用它。 If you don't want to delete the headers:如果您不想删除标题:

$("tbody").children().remove()

otherwise:否则:

$("table").children().remove()

hope it helps!希望能帮助到你!

If you can declare an ID for tbody you can simply run this function:如果你可以为tbody声明一个ID ,你可以简单地运行这个函数:

var node = document.getElementById("tablebody");
while (node.hasChildNodes()) {
  node.removeChild(node.lastChild);
}

the give below code works great.下面给出的代码效果很好。 It removes all rows except header row.它删除除标题行之外的所有行。 So this code really t所以这段代码真的

$("#Your_Table tr>td").remove();

I needed to delete all rows except the first and solution posted by @strat but that resulted in uncaught exception (referencing Node in context where it does not exist).我需要删除除@strat 发布的第一行和解决方案之外的所有行,但这会导致未捕获的异常(在不存在的上下文中引用 Node)。 The following worked for me.以下对我有用。

var myTable = document.getElementById("myTable");
var rowCount = myTable.rows.length;
for (var x=rowCount-1; x>0; x--) {
   myTable.deleteRow(x);
}

这将在本机的 HTML 表中进行迭代删除

document.querySelectorAll("table tbody tr").forEach(function(e){e.remove()})

Assing some id to tbody tag.为 tbody 标签分配一些 id。 ie . IE 。 After this, the following line should retain the table header/footer and remove all the rows.在此之后,以下行应保留表格页眉/页脚并删除所有行。

document.getElementById("yourID").innerHTML="";

And, if you want the entire table (header/rows/footer) to wipe out, then set the id at table level ie而且,如果您希望整个表格(页眉/行/页脚)消失,则在表格级别设置 id,即

How about this:这个怎么样:

When the page first loads, do this:首次加载页面时,请执行以下操作:

var myTable = document.getElementById("myTable");
myTable.oldHTML=myTable.innerHTML;

Then when you want to clear the table:然后当你想清除表时:

myTable.innerHTML=myTable.oldHTML;

The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.结果将是你的标题行,如果这就是你开始的全部,性能比循环快得多。

If you do not want to remove th and just want to remove the rows inside, this is working perfectly.如果您不想删除th并且只想删除里面的行,那么这是完美的。

var tb = document.getElementById('tableId');
  while(tb.rows.length > 1) {
  tb.deleteRow(1);
}

This works in IE without even having to declare a var for the table and will delete all rows:这在 IE 中有效,甚至无需为表声明一个 var 并将删除所有行:

for(var i = 0; i < resultsTable.rows.length;)
{   
   resultsTable.deleteRow(i);
}

Assign an id or a class for your tbody.为您的 tbody 分配一个 id 或一个类。

document.querySelector("#tbodyId").remove();
document.querySelectorAll(".tbodyClass").remove();

You can name your id or class how you want, not necessarily #tbodyId or .tbodyClass .您可以根据需要命名您的 id 或类,不一定是#tbodyId.tbodyClass

If you have far fewer <th> rows than non- <th> rows, you could collect all the <th> rows into a string, remove the entire table, and then write <table>thstring</table> where the table used to be.如果您的<th>行比非<th>行少得多,您可以将所有<th>行收集到一个字符串中,删除整个表,然后在表使用的位置写入<table>thstring</table>成为。

EDIT: Where, obviously, "thstring" is the html for all of the rows of <th> s.编辑:显然,“thstring”是<th>的所有行的 html。

this is a simple code I just wrote to solve this, without removing the header row (first one).这是我刚刚编写的一个简单代码来解决这个问题,没有删除标题行(第一个)。

var Tbl = document.getElementById('tblId');
while(Tbl.childNodes.length>2){Tbl.removeChild(Tbl.lastChild);}

Hope it works for you!!.希望这对你有用!!。

@lkan's answer worked for me, however to leave the first row, change @lkan 的回答对我有用,但是要离开第一行,请更改

from

for (var x=rowCount-1; x>0; x--)

to

for (var x=rowCount-1; x>1; x--)

Full code:完整代码:

var myTable = document.getElementById("myTable");
var rowCount = myTable.rows.length;
for (var x=rowCount-1; x>1; x--) {
   myTable.deleteRow(x);
}

Pure javascript, no loops and preserving headers:纯 javascript,没有循环并保留标头:

 function restartTable(){ const tbody = document.getElementById("tblDetail").getElementsByTagName('tbody')[0]; tbody.innerHTML = ""; }
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet"/> <table id="tblDetail" class="table table-bordered table-hover table-ligth table-sm table-striped"> <thead> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 2</th> <th>Header 2</th> </tr> </thead> <tbody> <tr> <td> a </td> <td> b </td> <td> c </td> <td> d </td> </tr> <tr> <td> 1 </td> <td> 2 </td> <td> 3 </td> <td> 4 </td> <tr> <td> e </td> <td> f </td> <td> g </td> <td> h </td> </tr> </tr> </tbody> </table> <button type="button" onclick="restartTable()">restart table</button>

只需清除表体。

$("#tblbody").html("");

Assuming the <table> element is accessible (eg by id), you can select the table body child node and then remove each child until no more remain.假设<table>元素是可访问的(例如通过 id),您可以选择表格主体子节点,然后删除每个子节点,直到不再存在。 If you have structured your HTML table properly, namely with table headers in the <thead> element, this will only remove the table rows.如果您的 HTML 表格结构正确,即在<thead>元素中使用表格标题,则只会删除表格行。

We use lastElementChild to preserve all non-element (namely #text nodes and ) children of the parent (but not their descendants).我们使用lastElementChild来保留所有非元素(即 #text 节点和 )父级(但不包括其后代)的子级。 See this SO answer for a more general example, as well as an analysis of various methods to remove all of an element's children.请参阅此 SO 答案以获取更一般的示例,以及对删除所有元素的所有子元素的各种方法的分析。

 const tableEl = document.getElementById('my-table'); const tableBodyEl = tableEl.querySelector('tbody'); // or, directly get the <tbody> element if its id is known // const tableBodyEl = document.getElementById('table-rows'); while (tableBodyEl.lastElementChild) { tableBodyEl.removeChild(tableBodyEl.lastElementChild); }
 <table id="my-table"> <thead> <tr> <th>Name</th> <th>Color</th> </tr> </thead> <tbody id="table-rows"> <tr> <td>Apple</td> <td>Red</td> </tr> <!-- comment child preserved --> text child preserved <tr> <td>Banana</td> <td>Yellow</td> </tr> <tr> <td>Plum</td> <td>Purple</td> </tr> </tbody> </table>

This will remove all of the rows except the <th> :这将删除除<th>之外的所有行:

document.querySelectorAll("td").forEach(function (data) {
  data.parentNode.remove();
});

Same thing I faced.我面临同样的事情。 So I come up with the solution by which you don't have to Unset the heading of table only remove the data..所以我想出了一个解决方案,你不必取消设置表的标题只删除数据..

 <script> var tablebody =document.getElementById('myTableBody'); tablebody.innerHTML = ""; </script>
 <table> <thead> </thead> <tbody id='myTableBody'> </tbody> </table>

Try this out will work properly...试试这个会正常工作...

const table = document.querySelector('table'); const table = document.querySelector('table'); table.innerHTML === ' ' ? table.innerHTML === ' ' ? null : table.innerHTML = ' ';空:table.innerHTML = ' '; the above javascript worked fine for me.上面的javascript对我来说很好。 It checks to see if the table contains any data and then clears everything including the header.它检查表是否包含任何数据,然后清除包括标题在内的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM