Error trying to change src of image using javascript

function changeImage(index) {
console.log(`${index+1}`);

var image1 = document.getElementById("img1");
image1.src = `images/${index+1}/1.png`;
}
function changeImage(index) {
console.log(`${index+1}`);

var image1 = document.getElementById("img1");
image1.src = `images/${index+1}/1.png`;
}
TypeError: image1 is null What's going on here? console.log returns "1" just fine, which is the name of the proper directory.
13 Replies
Mannix
Mannix•2mo ago
it means it can't find a element with id of img1
Kivory
KivoryOP•2mo ago
well it should be right here, did i mess something up here?
No description
Mannix
Mannix•2mo ago
where did you put your js code? in the head ?
Kivory
KivoryOP•2mo ago
yup
No description
Mannix
Mannix•2mo ago
weird you put defer on it so it should work try moving it before closing body tag
Kivory
KivoryOP•2mo ago
like putting it inside <body> </body>? just tried, nothing changed
Mannix
Mannix•2mo ago
well i'm stumped you need to wait for someone smarter to help you 😄
glutonium
glutonium•2mo ago
if the code is just html css and js then it would be nice if u can make a pen
glutonium
glutonium•2mo ago
CodePen
An online code editor, learning environment, and community for front-end web development using HTML, CSS and JavaScript code snippets, projects, and web applications.
Kivory
KivoryOP•2mo ago
I thought of something. Could it be that because there's two HTML files/pages, document.getElementById is trying to find the element in one html file and not the other, and that's why it's coming out null? I apologize if that was necessary info to state
glutonium
glutonium•2mo ago
it will look in the html it is linked to if u have js linked to say index.html but your image is in about.html which is not linking to js to it , js wont find it
Kivory
KivoryOP•2mo ago
okay, I'm trying to make it so that if you run changeImage() from index.html it specifically tries to find it from "example.html", and in example.html main.js is linked, how can I do this? i.e, I want to run the function after clicking a button in one html page, and having the function's effect be done in another html page.
Chris Bolson
Chris Bolson•2mo ago
This sounds rather confusing. Do you have example.html open within an iframe of index.html?
Want results from more Discord servers?
Add your server