英文:
how to make a clone of a column js?
问题
HTML
```html
<table>
<tr class="tab">
<td class="one">3</td>
<td class="one">4</td>
<td id="shes">5</td>
<td class="shee">6</td>
<td class="five">7</td>
<td class="six">8</td>
</tr>
</table>
JS
let elem = document.querySelectorAll('td.one');
elem.forEach((el) => {
el.insertAdjacentHTML('afterend', "<td>clone td.one(number)</td>");
});
英文:
HTMl
<table>
<tr class="tab">
<td class="one">3</td>
<td class="one">4</td>
<td id="shes">5</td>
<td class="shee">6</td>
<td class="five">7</td>
<td class="six">8</td>
</tr>
</table>
js
let elem = document.querySelectorAll('td.one');
elem.forEach((el) => {
el.insertAdjacentHTML('afterend', "<td>clone td.one(number)</td>");
});
how to clone column information ".one"
I tried using cloneNode but how to do it in .forEach don't understand
答案1
得分: 1
您可以使用 tr > td:nth-child(…)
,其中 …
是要复制的列的编号。然后使用 Element.after,它提供了一种插入相邻元素的简单方法 -
const col2 = document.querySelectorAll("tr > td:nth-child(2)")
for (const td of col2)
td.after(td.cloneNode(true))
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
</table>
这段代码可以在表格中复制第二列并将其插入到相邻的位置。
英文:
You could use tr > td:nth-child(…)
where …
is the number of the column to copy. Then use Element.after which offers a straightforward way to insert adjacent elements -
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const col2 = document.querySelectorAll("tr > td:nth-child(2)")
for (const td of col2)
td.after(td.cloneNode(true))
<!-- language: lang-html -->
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
</table>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论