简体   繁体   中英

I use insertBefore dom method to insert an element before another element.But it is not working at all

I want to append a div element before a specific element. I use the insertBefore dom method but not working. Here is the website link:

https://www.oflara.com

I want to add a button to this class = div.product-image.p .

Actually want to add a button before "ADD TO CARD" button.

Here is the image of a product_image class:

https://i.stack.imgur.com/EwXUL.png

 let product_images = document.querySelectorAll("div.product-image.pr"); const a_div = document.createElement("div"); a_div.className = "my_class"; console.log(product_images.length); for(let k =0; k<product_images.length; k++){ product_images[k].insertBefore(a_div,product_images[k].lastElementChild); //Not working }

var product_images = document.querySelectorAll("div.product-image.pr");
console.log(product_images.length);
for(let k =0; k<product_images.length; k++){
  var a_div = document.createElement("div");
  a_div.className = "my_class";
  product_images[k].insertBefore(a_div,product_images[k].lastElementChild); //Not working
}

The problem is that a_div is only 1 element. You need to create a new element and insert it for every instance.

Also note that the div won't be physically visible, but will be there if you search for it in the dev console. This is because it has no dimensions or inner content, so the height is 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM