如果给出id,我如何从DOM中删除一个元素?

时间:2010-07-14 09:07:36

标签: javascript html dom

在这种特定情况下,元素是表格行。

4 个答案:

答案 0 :(得分:6)

未经测试,但类似:

var tbl = document.getElementById('tableID');
var row = document.getElementById('rowID');
tbl.removeChild(row);

var row = document.getElementById('rowID');
row.parentNode.removeChild(row);

答案 1 :(得分:4)

var row = document.getElementById("row-id");
row.parentNode.removeChild(row);

答案 2 :(得分:2)

var zTag = document.getElementById ('TableRowID');
zTag.parentNode.removeChild (zTag);

或者在jQuery中:

$('#TableRowID').remove ();

答案 3 :(得分:0)

Jquery

$('#myTableRow').remove();

如果您的行有id,则可以正常工作,例如:

<tr id="myTableRow"><td>blah</td></tr>

纯Javascript:

Javascript Remove Row From Table

function removeRow(id) {
  var tr = document.getElementById(id);
  if (tr) {
    if (tr.nodeName == 'TR') {
      var tbl = tr; // Look up the hierarchy for TABLE
      while (tbl != document &amp;&amp; tbl.nodeName != 'TABLE') {
        tbl = tbl.parentNode;
      }

      if (tbl &amp;&amp; tbl.nodeName == 'TABLE') {
        while (tr.hasChildNodes()) {
          tr.removeChild( tr.lastChild );
        }
      tr.parentNode.removeChild( tr );
      }
    } else {
      alert( 'Specified document element is not a TR. id=' + id );
    }
  } else {
    alert( 'Specified document element is not found. id=' + id );
  }
}