Javascript删除表格tbody标签 [英] Javascript delete a table tbody tag

查看:147
本文介绍了Javascript删除表格tbody标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用下面的代码在vanilla Javascript中删除行:

  var table = document.getElementById('table') ;函数deleteRow(){ta​​ble.deleteRow(1);};  

table {background:#ccc;宽度:100%; } table thead {background:#333;颜色:#fff; } table tbody {background:magenta;颜色:#fff; }

< button onclick =deleteRow()> ;删除行< / button>< table id =table> < THEAD> < TR> < TD> FOO< / TD> < TD>巴≤; / TD> < / TR> < / THEAD> < TBODY> < TR> < TD> LOREM< / TD> < TD> ipsum的< / TD> < / TR> < / tbody的> < TBODY> < TR> < TD> LOREM< / TD> < TD> ipsum的< / TD> < / TR> < / tbody的> < / table>



但是这段代码留下了一个空的tbody标签behing。 JS有删除thead和tfoot元素的方法,但它似乎缺少一个 deleteTbody 一个。



我应该如何使用纯javascript来移除 tbody 及其所有内容?没有jQuery的,请!!

解决方案

如果你想删除 tbody 标签,您可以选择行本身而不是表格,然后使用 removeChild 函数。

  var table = document.getElementById('table'); 
var row = document.getElementsByTagName('tbody')[0];


函数deleteRow(){
row.parentNode.removeChild(row);
};


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!

解决方案

If you want to remove the tbody tag, you could select the row itself rather than the table, then use the removeChild function.

var table = document.getElementById('table');
var row = document.getElementsByTagName('tbody')[0];


function deleteRow () {
    row.parentNode.removeChild(row);
};

这篇关于Javascript删除表格tbody标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆