HTML DOM Table 对象

htmlweb developmentfront end technology更新于 2025/7/17 23:40:17

HTML DOM Table 对象表示 HTML 文档的 <table> 元素。

让我们看看如何创建表格对象

语法

以下是语法 −

document.createElement(“TABLE”);

属性

以下是 Table 表格对象的属性 −

属性说明
caption它返回 <caption> HTML 文档中表格的 <tfoot> 元素。
tFoot返回 HTML 文档中表格的 <tfoot> 元素。
tHead返回 HTML 文档中表格的 <thead> 元素。

方法

以下是 Table 表格对象的方法 −

方法说明
createCaption()生成一个空的 <caption>元素并将其添加到表中。
createTFoot()生成一个空的 <tfoot> 元素并将其添加到表中。
createTHead()生成一个空的 <thead> 元素并将其添加到表中。
deleteCaption()从表中删除第一个 <caption> 元素。
deleteRow()从表中删除一个 <tr> 元素。
deleteThead()删除 <thead>元素从表格中删除。
deleteTFoot()它从表格中删除 <tfoot> 元素。
insertRow()它生成一个空的 <tr> 元素并将其添加到表格中。

示例

让我们看一个表格对象的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      text-align: center;
      background-color: #fff;
      color: #0197F6;
   }
   h1 {
      color: #23CE6B;
   }
   .btn {
      background-color: #fff;
      border: 1.5px dashed #0197F6;
      height: 2rem;
      border-radius: 2px;
      width: 60%;
      margin: 2rem auto;
      display: block;
      color: #0197F6;
      outline: none;
      cursor: pointer;
   }
</style>
</head>
<body>
<h1>DOM table Object Demo</h1>
<button onclick="createTable()" class="btn">Create a table object</button>
<script>
   function createTable() {
      var table = document.createElement("TABLE");
      table.innerHTML = `<tr>
      <td>Data 1</td>
      <td>Data 2</td>
      </tr>
      <tr>
      <td>Data 3</td>
      <td>Data 4</td>
      </tr>`;
      table.setAttribute('border', "2");
      table.style.margin = "2rem auto";
      document.body.appendChild(table);
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击“创建表格对象”按钮来创建表格对象。


相关文章


有用资源