簡體   English   中英

附加到所有具有相同類別的div

[英]Append on all divs with same class

我正在嘗試更改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行,使其位於循環內。

一個元素只能附加到單個div。 考慮制作一個函數,該函數返回要附加的新元素:

function createWrapper()
{
    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";
    return product_item_wrapper;
}

var divjes = {};
divjes = document.getElementsByClassName("product-type-simple");
for (var i = 0; i < divjes.length; i++)
{
    divjes[i].appendChild(createWrapper());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM