您好,我正在尝试将多个表插入div。
例如,我的文档中有多个表格
<table>
<tr>
<th>1</th>
<th>2</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
现在我要选择它们:
table = document.getElementsByTagName("TABLE");
使用类"tablediv"
创建div
并将每个表添加到"tablediv"
,例如:
<div class="tablediv">
<table>
...
</table>
</div>
纯js是否有可能?
有可能做类似的事情
var table = document.getElementsByTagName("TABLE");
var div = document.getElementById('tablediv');
div.innerHTML += table;
不确定document.getElementsByTagName("TABLE");
输出,您可能需要使用额外的属性来访问诸如innerHTML之类的html,如果是数组,则可能需要在循环中使用它。
如果我正确理解,我认为您可以使用模板文字。参见this link
您可以执行以下操作:
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>