代码之家  ›  专栏  ›  技术社区  ›  darksoulsong

Javascript删除表tbody标记

  •  6
  • darksoulsong  · 技术社区  · 10 年前

    我知道我可以使用以下代码来删除香草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>

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

    我该如何删除 tbody 所有内容都只使用纯javascript?请不要jQuery!

    5 回复  |  直到 10 年前
        1
  •  11
  •   MaVRoSCy    10 年前

    尝试使用:

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

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

        2
  •  3
  •   Rick Hitchcock    10 年前

    使用 querySelectorAll() 遍历所有 TBODY 元素,然后删除那些没有子元素的元素:

    var table = document.getElementById('table');
    
    function deleteRow() {
      table.deleteRow(1);
    
      var tb = document.querySelectorAll('tbody');
      for (var i = 0; i < tb.length; i++) {
        if (tb[i].children.length === 0) {
          tb[i].parentNode.removeChild(tb[i]);
        }
      }
    };
    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>
        3
  •  2
  •   Galen Cook    10 年前

    如果要删除 tbody 标记,您可以选择行本身而不是表,然后使用 removeChild 作用

    var table = document.getElementById('table');
    var row = document.getElementsByTagName('tbody')[0];
    
    
    function deleteRow () {
        row.parentNode.removeChild(row);
    };
    
        4
  •  0
  •   Ryan Sayles    10 年前

    没有 deleteTbody 但是有 removeChild :

    var parent = document.getElementById("parent-id");
    var child = document.getElementById("child-id");
    parent.removeChild(child);
    
        5
  •  0
  •   suba    4 年前

    我希望它能帮助你。我很抱歉。现在回答太晚了。

    tbody数据是tbody的id值。

    $("#tbody-data tr").remove();