通过 JavaScript 将表格插入 div

Insert tables into div via JavaScript

您好,我正在尝试将多个 table 插入 div。

我的文档中有多个 table,例如

<table>
   <tr>
      <th>1</th>
      <th>2</th> 
   </tr>
   <tr>
      <td>1</td>
      <td>2</td>
   </tr>
</table>

现在我想select他们:

table = document.getElementsByTagName("TABLE");

用 class "tablediv"

创建 div

并将每个 table 添加到 "tablediv",例如:

<div class="tablediv">
   <table>
      ...
   </table>
</div>

纯js可以吗?

这样做是有可能的

var table = document.getElementsByTagName("TABLE");
var div = document.getElementById('tablediv');
div.innerHTML += table;

不确定 document.getElementsByTagName("TABLE"); 输出,您可能需要使用额外的属性来访问 html,例如 innerHTML,如果它是一个数组,您可能需要在循环中使用它。

你可以这样做:

let divTable = document.createElement("div"); //create new <div>
divTable.id = "tablediv";

let tables = document.getElementsByTagName("table"); //HTMLCollection which is live, no need to delete "old tables"
while (tables.length > 0) divTable.append(tables[0]); //add every <table> to the new <div>

let body = document.querySelector("body"); //change to the preferred selector
body.append(divTable); //append new <div> to the selected Element, in this case <body>

运行这个解决方案。它有 4 张桌子。单击按钮,所有表格都将添加到 DIV。

function gatherTables(){
  var all_tables = document.getElementsByTagName('table');
  var tableCollectionDiv = document.getElementById('tablediv');
  
  tableCollectionDiv.innerHTML = '';
  Array.prototype.forEach.call(all_tables, a => {
    tableCollectionDiv.appendChild(a.cloneNode(true));
  });
}
table td, table th {
  border: 2px solid #ddd;
  padding: 6px;
}

#tablediv{
  background-color:  #8AC7DB;
  height: 500px;
}

body{
  background-color:#338BA8;
}

#tablediv > table{
  margin-top: 20px; 
  margin-bottom: 20px;
}

button{
  background-color: #75E6DA;
}
<table>
   <tr>
      <th>1a</th>
      <th>2a</th> 
   </tr>
   <tr>
      <td>1a</td>
      <td>2a</td>
   </tr>
</table>

<br>
<table>
   <tr>
      <th>1b</th>
      <th>2b</th> 
   </tr>
   <tr>
      <td>1b</td>
      <td>2b</td>
   </tr>
</table>
<br>
<table>
   <tr>
      <th>1c</th>
      <th>2c</th> 
   </tr>
   <tr>
      <td>1c</td>
      <td>2c</td>
   </tr>
</table>


<br>
<table>
   <tr>
      <th>1d</th>
      <th>2d</th> 
   </tr>
   <tr>
      <td>1d</td>
      <td>2d</td>
   </tr>
</table>

<br>
<button onclick="gatherTables()">Gather Tables Now</button>
<br>
<hr>
 DIV start
<div id="tablediv"></div>
 DIV end