javascript - 如何连接两个html元素?
问题描述
我有 2 个类似的 HTML 表格类,我将它们称为htmlelement并希望将它们连接起来。它类似于我的代码:
var first = document.getElementsByClassName("firstclass") as HTMLCollectionOf<HTMLElement>;
var second = document.getElementsByClassName("secondclass") as HTMLCollectionOf<HTMLElement>;
for(var i=0;i<secondclass.length;i++){
firstclass.appendChild(secondclass.item(i));
}
但它不起作用。Concat
功能也不起作用。
这类似于一个类。
<body>
<tr class="first">
<td id="one_{{i}}" class="col" (change)="typeAdd()" ondrop="drop(event)" ondragover="allowDrop(event)">
</td>
<td id="second_{{i}}" class="col" ondrop="drop(event)" ondragover="allowDrop(event)">
</td>
</tr>
</tbody>
解决方案
只需使用数组析构函数即可,有关更多信息,请参阅解构赋值。
并将元素附加到目标父级
var first = document.getElementsByClassName("firstclass"),
second = document.getElementsByClassName("secondclass"),
containerElement = document.querySelector("#some-container"),
both = [...first, ...second];
both.forEach(e => containerElement.appendChild(e));
#some-container {
background-color: lightgreen;
color: white;
font-size: 20px;
padding: 10px;
}
<div id="some-container"></div>
<p class="firstclass">first class 1</p>
<p class="firstclass">first class 2</p>
<p class="firstclass">first class 3</p>
<p class="secondclass">second class 1</p>
<p class="secondclass">second class 2</p>
<p class="secondclass">second class 3</p>
推荐阅读
- c# - HtmlInputRadioButton 有静态 ID's-ClientIDmode=static 不起作用
- python - 用python进行数值二阶微分
- reactjs - Passport Facebook 无法使用 React 应用程序
- composer-php - 使用 composer 安装同一库的多个版本
- rest - 如何在 swagger2.0 中制作两个控制器(参数不同)?
- javascript - 如何在 JavaScript 中对当前行进行计算
- c# - 在创建之前由 foreach 访问 ShadowProperties
- asp.net-core - 在 asp.net core 中的项目之间共享配置文件
- events - 重用默认键盘事件处理程序
- powershell - 使用 PowerShell 更改 .csv 中的 samaccountname