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:
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.