k r harsha k r harsha - 1 year ago 129
Javascript Question

how to change the img.src value in javascript

I have a code in JavaScript where it creates an HTML page, just a div and an image tag. The tricky part for me is I'm trying to generate/populate this image tag with

img.src
value with the help of an if statement.

The code goes something like this.



var propertyname;
var content = document.createElement('div');
var img = document.createElement('img');
if (propertyname == 'house') {
img.src = 'house.jpg';
}
content.appendChild(img);





How can I make this code better. Right now the image is not being inserted when I check in the developer tools for Chrome the
img.src
is
undefined
.

Thanks in advance.

Answer Source

It's working fine when your propertyname variable has a value.

var propertyname = 'house';

var content = document.createElement('div');
var img = document.createElement('img');

if (propertyname == 'house') {
  img.src = 'https://placehold.it/300x100';
}

content.appendChild(img);
document.getElementsByTagName('body')[0].appendChild(content);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download