Click here to Skip to main content
14,695,085 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a chrome extension so you can download images when clicking on them. The problem is that it is a bit buggy, so any help would be awesome. Here is the javascript:

var myImg = document.querySelector('img');
myImg.addEventListener("click", () => {
var a = document.createElement('a');
a.href = myImg.src; = myImg.src;

The problem is it doesnt allways work on websites, and it only works if there is one image, how can I change this? Is there a way to make it so it only downloads the image you click on and not all of them?

What I have tried:

I would assume that maybe you should add an id to the image that the user clicks on, then download the value of the id. But I am not sure how to do that. Thank you so much for any help you might give. Have a good day!
Updated 29-Aug-20 4:58am

The reason it works for one and not all, above code has to be applied for all the elements.
You use: query selector
The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.

You need to find all img tags and add click handler to all:
// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
    var imgElements = document.body.getElementsByTagName("img");  // gets all the iamges of webpage imgElements, function ( el ) {  // loops through all the images
        el.addEventListener("click", () => {.                     // attaches click handler one by one
            var a = document.createElement('a');
            a.href = el.src;
   = el.src;

Take cue from here: How to Build a Chrome Extension | Chapter 6: How to replace images on a website with your own images | Heptagon[^]

PS: Above code is more from my memory and might need some change. Intent is to share what could be done and where is the gap. Try out.

$(document).ready(function () {
$("img").click(function () {
var t = document.createElement('a');
t.href = this.src; = this.src;

please try this code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900