Chrome Extension add button to each image on a page

Viewed 424

I am trying to append a button to each image on a webpage using a Chrome Extension. I have the following code in my content script:

var imagesArray = document.getElementsByTagName("img");
console.log(imagesArray);

for (const img of imagesArray) {
    var button = document.createElement("button");
    button.innerHTML = "button";
    button.onclick = function() {
        console.log("clicked");
    }
    
    img.append(button);

}

I am able to get all the images and I know I can append buttons, I just don't know how to append the button onto the image. Any help is appreciated

2 Answers

Use this line document.body.appendChild(button); <-- use this line down this img.append(button)

You can use something like this in the css. If you are able to add any css. Thanks

button {
  display: none;
}

img:hover + button {
  display:block;
}
<img src="https://picsum.photos/id/237/200/300" />
<button>My Button</button>

Related