InnerHTML not showing image in array

I have been trying to add the image to the array and make it appear on the DOM using InnerHTML but for some reason its no working at all and Im just getting a simple “[object HTMLImageElement]” message CODEPEN

<!DOCTYPE html> 

	<title>Adding object in array</title> 
		body { 
			text-align: center; 
        #geeks {
            color: purple;
            font-size: 25px;
            font-weight: bold;

	<h1 style="color: green">Geeksforgeeks</h1> 
	<p>Click the button to add new elements to the array.</p> 

	<p id="geeks"></p> 

		var list = ["One", "Two", "Three"]; 
        var img = document.createElement("img");
        img.src = "";
		document.getElementById("geeks").innerHTML = list; 



Can you explain what you’re actually trying to do? ATM you’re pushing an HTML element (an object) into an array. If you give innerHtml a valid element, it’ll render an element. If you give it some text, it’ll render the text. You’re giving it an array. It can’t do anything with that, so it converts the array to a string then renders that string

This is what an innerHTML call should look like:

innerHtml("<img src="" />")

It takes a string representation of some HTML.

An array is not a string, so JS converts it to a string. The image is an object (HTMLImageElement). That gets converted to a string (so that’s [object HTMLElement]).

appendChild or similar would be used to append an actual HTML element object.

But you’re still trying to use an array.

thanks alot I will keep trying

1 Like

Do you understand that the function innerHtml takes a string, so

  • if you give it an array, it will convert that array into a string
  • converting an object into a string results in [object TheTypeOfTheObject]

You can’t do what you’re trying to do. If you have an array of HTML elements, you need to loop over the array and use something like the appendChild function to render them. You have an array of some strings and an HTML element, so you can’t even just do that


hey @codeca423

this should solve your problem, if you want it to display inline add display:flex; to your geeks element, probably best to change it to a div too :slightly_smiling_face: :+1:

var list = ["One", "Two", "Three"];
var img = document.createElement("img");
let geeks = document.getElementById("geeks");
img.src = "";
list.forEach(x => {
  let para = document.createElement('p')
  typeof x === 'string' ?
    para.innerText = x : para = x

1 Like

:wave:t4: @codeca423,

you could check for object like elements in your array list and change to appendChild when needed

    var list = ['One', 'Two', 'Three'];
      var img = document.createElement('img');
      img.src =
      let span = document.createElement('span');
      list.forEach(i => {
                 if(typeof i === "object"){
                 span.innerHTML +=" "+i+" ";

1 Like