HTML DOM Table insertRow() 方法

htmlweb developmentfront end technology更新于 2025/11/28 18:52:17

HTML DOM Table insertRow() 方法生成一个空的 <tr> 元素,并将其添加到 HTML 文档的表格中。

语法

以下是语法 −

object.insertRow(index)

其中,index 表示要插入行的位置。

让我们看一个 HTML DOM 表格 insertRow() 方法的示例 −

示例

<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      background: lightblue;
      height: 100vh;
      text-align: center;
   }
   table {
      margin: 2rem auto;
   }
   caption {
      color: #db133a;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   .show {
      font-size: 1.2rem;
   }
</style>
<body>
<h1>DOM Table insertRow() Method Demo</h1>
<table border="2">
<tr>
<td>Name</td>
<td>Roll No.</td>
</tr>
<tr>
<td>John</td>
<td>071717</td>
</tr>
<tr>
<td>Jane</td>
<td>031717</td>
</tr>
</table>
<button onclick="create()" class="btn">Create Row</button>
<script>
   function create() {
      var table = document.querySelector('table');
      var tableRow = table.insertRow(1);
      tableRow.innerHTML = "<td>Maximilian</td><td>081717</td>";
   }
</script>
</body>
</html>

输出

点击"创建行"按钮为表格创建新行。


相关文章


有用资源