首页 > 解决方案 > 如何连接两个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>

标签: javascripthtmldom

解决方案


只需使用数组析构函数即可,有关更多信息,请参阅解构赋值

并将元素附加到目标父级

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>


推荐阅读