John
John

Reputation: 77

Webpage isn't rendering pictures added using Javascript

I am trying to add an image to a website using Javascript. I am doing this using createElement, and setAttribute to point to the image in my file directory. Here is the very basic code:

var lambda = document.createElement("img");
lambda.setAttribute("src", "img/512.png");
var body = document.querySelector("body");
body.prepend(lambda);

I am confused because when the website loads, the image does not render properly. However, when I inspect the broken image and copy/paste the html from my browser into my html document and then reload, the image loads properly. My question is, why is the browser unable to load the image when I call it using Javascript, but it works perfectly when the code generated by Javascript is copied into the html document?

Upvotes: 3

Views: 89

Answers (1)

mplungjan
mplungjan

Reputation: 177975

Try this to see what is going on, and then look in the network tab to see what is loaded

const imgSrc = "img/512.png"; // "https://cdn.iconscout.com/icon/premium/png-512-thumb/lambda-2-550999.png"; 
const lambda = document.createElement("img");
lambda.onload = function() {document.querySelector("body").prepend(lambda)}
lambda.onerror = function(err) { console.log(err,err.path) }
lambda.setAttribute("src",imgSrc);

For example for your image URL I get this in the network console

Request URL: https://stacksnippets.net/img/512.png
Request Method: GET
Status Code: 404 Not Found

Upvotes: 1

Related Questions