我正在尝试更改 WooCommerce 的布局,但由于我无法正常工作,所以我决定通过使用 Javascript 创建一个 div 并将其附加到现有 div 来按照我的意愿更改它。我确实有一些行穿过具有特定类的每个 div,但只有当我让它们更改innerHTML 时才有效。但是当我使用appendChild时,它只附加到最后一个div。有人知道可能是什么吗?这是我使用的代码。类“product-type-simple”是已经存在的 div。
var product_item_wrapper = document.createElement("div");
product_item_wrapper.style.width = "100px";
product_item_wrapper.style.height = "100px";
product_item_wrapper.style.background = "red";
product_item_wrapper.style.color = "white";
product_item_wrapper.innerHTML = "Hello";
product_item_wrapper.className = "product";
var divjes = document.getElementsByClassName("product-type-simple");
for(var i = 0; i < divjes.length; i++){
divjes[i].appendChild(product_item_wrapper);
}
最佳答案
您正在创建一个元素。然后将其附加为多个元素的子元素。每次执行此操作时,都会将其从之前的位置删除并将其放置在新元素中。
如果您想要多个元素,那么您需要创建多个元素。
移动代码的前 7 行,使它们位于循环内。
关于javascript - 追加到具有相同类的所有 div 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550370/