3

I'm wanting to get an image to display using innerHTML and I just can't seem to get it to work. It works fine with text and I'm trying to get it to display dynamically with other items inside innerHTML. Updated: the image is inside another element in the innerHTML. Image Example:

    var div = document.createElement('div');
    var image = document.createElement('img');
    image.setAttribute('src', "https://picsum.photos/200/300");/*sample pic*/
    div.innerHTML = '<a href="/"><h3>title</h3>'+ image + '</a>';
    document.getElementById('block').appendChild(div);/*work fine if appendChild(image) or text inside innerHTML*/
<div id="block">
  image
</div>
Victoria Le
  • 860
  • 6
  • 15

6 Answers6

2

innerHtml is used to parse a string as HTML code.

To attach the image to the DOM element use:

div.appendChild(image);
rufus1530
  • 765
  • 4
  • 19
2

Use .appendChild() on the image to make it a child of the div, instead of innerHTML:

var div = document.createElement('div');
    var image = document.createElement('img');
    image.setAttribute('src', "https://picsum.photos/200/300");/*sample pic*/
    div.appendChild(image);
    document.getElementById('block').appendChild(div);/*work fine if appendChild(image) or text inside innerHTML*/
<div id="block">
  image
</div>

See "innerHTML += ..." vs "appendChild(txtNode)" for the differences in the two

j08691
  • 204,283
  • 31
  • 260
  • 272
2

The recommended way of adding an image would be via appendChild(), however to add an image element in the way you require, you'd need to specify the image in terms of its HTML tag and attributes as html, as follows:

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

    // Define the image tag and html directly and then apply to innerHTML in this way
    div.innerHTML = '<img src="' + "https://picsum.photos/200/300" + '" />';

    document.getElementById('block').appendChild(div);
<div id="block">
  image
</div>
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
2

Use this code instead of innerHTML

var div = document.createElement('div');
var image = document.createElement("img");
image.setAttribute('src', "https://picsum.photos/200/300");/*sample pic*/
document.getElementById('block').appendChild(div).appendChild(image);
sonysadi
  • 69
  • 1
  • 9
0

you need to use appendChild instead of innerHTML:

    var div = document.createElement('div');
    var image = document.createElement('img');
    image.setAttribute('src', "https://picsum.photos/200/300");
    div.appendChild(image);
    document.getElementById('block').appendChild(div);
<div id="block">
  image
</div>
Andreas
  • 69
  • 3
0

You could change this line div.innerHTML = image;

To this: div.innerHTML = image.outerHTML;

You're setting the innerHTML to an object currently instead of to html.

CamJohnson26
  • 1,119
  • 1
  • 15
  • 40