On click doesn't work

Hi guys, I’m trying to make an image changer using Javascript
and there’s always that error in the console

main.js:50 Uncaught ReferenceError: i is not defined at HTMLImageElement.myImage.onclick (main.js:50)

Here’s my HTML code

<!DOCTYPE html>

                hello world
    <img src="1.jpg" alt="myimage"  >
        <script src="main.js"> 

and this is Javascript code

let myImage= document.querySelector('img');
myImage.onclick= function ()
    let mysrc= myImage.getAttribute('src');

Hi Ola,

It looks like the copy paste of your JS code didn’t work, can you try it again please :slight_smile: ?

oh I’m sorry I’ll try posting it again

I’ve updated it just now …

No problem ;),

Is that all your code ?
I am beginner but for the little I know the problem come from this part :


What is i.jpg ? I guess you wanted yo use a counter that become “1.jpg”, “2.jpg” etc. But none is declared. Furthermore I am not sure il would work like this. Maybe you should try to put “.jpg” between quote marks and concatenate it with i.

1 Like

Back tracking to what Meditsh stated, JS is trying to look for the property i.jpg, you would need to wrap it in quotes if you are trying to compare against a string, or concatenate the i, if it’s a counter to the string “jpg”. If it’s the second issue, I would recommend using template string literals instead, as it’s easier to read and understand.


Wow I didn’t even notice that I wrote “i” instead of 1 …thanks alot!