2

trying to add an image to my innerHTML.

Looked at a few prvious Q's Why does my image not show up when I use Javascript innerHTML to call it?

Javascripts innerHTML not working for images, but works with text?

I cant get it working, in google dev tools throws the error:

Uncaught TypeError: Cannot set property 'innerHTML' of null 

with this line:

var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>"; 

my code looks like:

 function showImage() { var img = document.createElement('image'); //var newImage = document.getElementById('img').innerHTML = "<a href='#'><img src='http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg' border=0/></a>"; var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>"; var div5 = document.createElement('div'); div5.appendChild(newImage); return div5.innerHTML; } 

I know there are many other methods to display an image, but for the purpose of this exercise I want to return the image as an innerHTML

5
  • 1
    Why use document.getElementById('img')? Is the image like this: <img id="img">? Commented Nov 13, 2014 at 15:49
  • 2
    @ekad: img tags have no inner html anyways. they're a singleton tag. it'd have to be <div id="img"></div> or something. Plus, why create an image tag, and then never use it? img.src="images/bg-main.jpg"; would do just as well. OP's got some seriously schizophrenic code there. Commented Nov 13, 2014 at 15:49
  • technically you would need outerHTML to encompass the tag too, but even then I'm not sure it would work. Commented Nov 13, 2014 at 15:50
  • Something I see that may be a problem is your src path. I think you would need it to be <img src='/images/bg-main.png></img>. Notice the backslash at the beginning of the path. Commented Nov 13, 2014 at 15:51
  • No mental issues thanks guys just beginning to learn JS..loads a fun Commented Nov 13, 2014 at 16:43

2 Answers 2

2

Try this :

var img = document.createElement("img"); img.setAttribute('src', 'http://www.domain.com/imgSrc'); var div5 = document.createElement('div'); div5.appendChild(newImage); 
Sign up to request clarification or add additional context in comments.

Comments

0

document.createElement('image') creates a new html tag: <image> i suspect you're trying to add a div and apply the image as inner html. you can fix this code like the following:

function showImage() { var img = document.createElement('div'); document.body.appendChild(img) img.innerHTML = "<img src='images/bg-main.png></img>"; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.