gpt4 book ai didi

javascript - appendChild 未能将相同的元素附加到相同的类元素之一?

转载 作者:行者123 更新时间:2023-12-02 21:19:34 25 4
gpt4 key购买 nike

请参阅here .

我们有这样的 JavaScript 代码:

document.addEventListener("DOMContentLoaded", function(event) {

let source_elem = document.querySelector('.ProductMeta__Description .Rte .TableWrapper table');

let size_table = source_elem.cloneNode( true );

let hooks = document.querySelectorAll('.product-desc-table-clone');
console.log('size: ' + hooks.length);
for (i = 0; i < hooks.length; ++i) {
hooks[i].appendChild( size_table );
console.log(i);
}

});

它将尺码表附加到具有 product-desc-table-clone 类的 2 个 div 元素。奇怪的是,只有第二个元素被附加到表格中。

为什么?

最佳答案

Node.appendChild()

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

您可以使用innerHTMLElement.insertAdjacentHTML() .

演示:

document.addEventListener("DOMContentLoaded", function(event) {

let source_elem = document.querySelector('.ProductMeta__Description .Rte .TableWrapper table');
let size_table = source_elem.cloneNode(true);
let hooks = document.querySelectorAll('.product-desc-table-clone');
console.log('size: ' + hooks.length);
for (i = 0; i < hooks.length; i++) {
hooks[i].insertAdjacentHTML('beforeend', size_table.outerHTML);
console.log(i);
}

});
<div class="ProductMeta__Description">
<div class="Rte">
<div class="TableWrapper">
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
</div>
</div>
</div>

<div class="product-desc-table-clone"></div>
<div class="product-desc-table-clone"></div>

关于javascript - appendChild 未能将相同的元素附加到相同的类元素之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60886766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com