Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why wont .innerHTML display images?

I can get the 'button.png' to change to text, but not to an image...

Can you please post your code, so we can see what's going on.

Here is my code...

<p id="demo"><img src="IMG/button.png" alt=""</p>
        <script>
document.getElementById("demo").onclick = function() {myFunction()};
          var retvalue = Math.floor((Math.random() * 10) + 1);
function myFunction() { 
          var repImage;
if (retvalue == 1)   {               
  repImage = "<img src='IMG/emoji 1.png'>";
} else if (retvalue == 2) {
  repImage = "<img src='IMG/emoji 2.png'>";
} else if (retvalue == 3) {
  repImage = "<img src='IMG/emoji 3.png'>";
} else if (retvalue == 4) {
  repImage = "<img src='IMG/emoji 4.png'>";
} else if (retvalue == 5) {
  repImage = "<img src='IMG/emoji 5.png'>";
} else if (retvalue == 6) {
  repImage = "<img src='IMG/emoji 6.png'>";
} else if (retvalue == 7) {
  repImage = "<img src='IMG/emoji 7.png'>";
} else if (retvalue == 8) {
  repImage = "<img src='IMG/emoji 8.png'>";
} else if (retvalue == 9) {
  repImage = "<img src='IMG/emoji 9.png'>";
} else {
  repImage = "<img src='IMG/emoji 10.png'>";
document.getElementById("demo").innerHTML = repImage; }
</script>
Colin Bell
Colin Bell
29,679 Points

You could cut down a lot of your code if that's how you've named your image files

var demo = document.getElementById("demo");
var retvalue = Math.floor((Math.random() * 10) + 1);

demo.onclick = myFunction;

function myFunction() { 
  demo.innerHTML =  "<img src='IMG/emoji " + retvalue +  ".png'>";
}

js bin - pictures will be broken since I don't have them, but I've console.log() the innerHTML so you can see it's there

And if you wanted a different random image to appear every time you clicked, you'd just move the retvalue to inside of the function:

var demo = document.getElementById("demo");
demo.onclick = myFunction;

function myFunction() { 
  var retvalue = Math.floor((Math.random() * 10) + 1);
  demo.innerHTML = "<img src='IMG/emoji " + retvalue +  ".png'>";
}

2 Answers

Ognjen Jevremovic
Ognjen Jevremovic
13,028 Points

Hello Ross. How are you doing?

The

object.innerHTML 

propertie takes the current content of the HTML element (object in this case) and updates it; meaning it takes the current content of an HTML element and it completely overrides it with the content you provided it with. It can either be used to update a text of the paragraph or perhaps to insert a new HTML element in the webpage, as a descendant of the HTML element (presented as "object" in the example above).

Note that, HTML elements are nothing more than just a string values inside of the JavaScript. They don't have any particular meaning, because they're wrapped with quotes, just as any other string values are in JavaScript programming language, so they are interpreted as a text inside of the JS document. However, when that string value is properly styled (as HTML elements are - <tagname attribute="somevalue">) and inserted into HTML document, they will take a the actual form of an HTML element and will be rendered on the webpage as one.

In particular, .innerHTML propertie can be used to insert any HTML element tag you'd like, as once again inside of JS it's still a plain text. I've noticed a few bugs in your code and I manged to tweak it arround a bit. Here's the forked version of the working JavaScript code with a few explanations alongside with it:

/* Get the HTML element from the webpage with an ID "demo" */
document.getElementById("demo").onclick = function() {

    /* Call for a custom made function */
    myFunction();
} 

/* Generate a randon number between 1 and 10 */
var retvalue = Math.floor((Math.random() * 5) + 1); 


/* Custom function that will check the random number generated and insert a particular image (based on the random number generated and stored in the "retvalue" variable) into the HTML element with ID name "demo" */
function myFunction() { 

    /* Create a variable that will hold  the text and when inserted into HTML document it will be rendered as an HTML img element */
    var repImage = '<img src="'; 

    /* Conditional that will update the src attribute value of the img element and close the img tag aswell; the content of the updated repImage variable will be embeded in the HTML document */
    if (retvalue == 1) {

        /* random img src 1 */
        repImage += 'http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg">'; 
    } else if (retvalue == 2) {

        /* random img src 2 */
        repImage += 'http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg">'; 
    } else if (retvalue == 3) {

        /* random img src 3 */
        repImage += 'http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg">'; 
    } else if (retvalue == 4) {

        /* random img src 4 */
        repImage += 'http://www.hdwallpapersimages.com/wp-content/uploads/images/Child-Girl-with-Sunflowers-Images.jpg">'; 
    } else if (retvalue == 5) {

        /* random img src 5 */
        repImage += 'http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg">'; 
    } else if (retvalue == 6) {

        /* random img src 6 */
        repImage = 'http://www.planwallpaper.com/static/images/wallpaper-sunset-images-back-217159.jpg">'; 
    } else if (retvalue == 7) {

        /* random img src 7 */
        repImage = 'http://www.planwallpaper.com/static/images/2511289_GFurDeb_GScpebr.jpg">'; 
    } else if (retvalue == 8) {

        /* random img src 8 */
        repImage = 'http://www.planwallpaper.com/static/images/magic-of-blue-universe-images.jpg">'; 
    } else if (retvalue == 9) { 

        /* random img src 9 */
        repImage = 'http://www.planwallpaper.com/static/images/6986083-waterfall-images_Mc3SaMS.jpg">'; 
    } else { 

        /* random img src 10 */
        repImage = 'http://www.planwallpaper.com/static/images/background-gmail-google-images_FG2XwaO.jpg">'; 
    }

    /* Insert the string content of the repImage variable to the HTML document; the string value stored in the variable, when inserted into HTML document will be rendered as the atual HTML img element */    
    document.getElementById("demo").innerHTML = repImage;
}

Here's the code including markup, some basic styles and the code provided. Feel free to tweak it arround to suite your needs. Hope that helps! If not, feel free to provide us with additional info, so we can inspect the code in full details = ).

Happy coding and keep on hacking!

Wow...thank you so much. A couple more questions. I still cant seem to get it to work when referencing an actual image (for example: 'IMG/emoji 8.png'>" ). Also, why do you sometimes use the "+=" operator for repImage and other times use "="?

Ognjen Jevremovic
Ognjen Jevremovic
13,028 Points

You're more than welcome Ross. We're all here to help each other learn = ).

It must be an error regarding the file path. Did you check you didn't make any typos while refrencing the image? Also, I'm not entirely sure about the spaces in the HTML code, as I think they're replaced with a combination of characters such as like "%20" or something similar. Could you perhaps rename the image to something like "emoji_8.png" instead and try it like that (of course by updating both the name of the image, aswell as the filepath - src attribute of the img element). Or anything else, that just don't have the space in it's name.

The difference between the operators " = " and " += " is that the plus equal sign takes the current value of a variable and adds up a new value (the value to the right of the equal sign) to it. For example, let's consider the code:

var myFavoriteNumber = 5;

myFavoriteNumber = 10   
/* This will update the value of the variable and will replace the current value (which was number 5) and replace it with a number 10, whereas: */

var mySecondFavoriteNumber = 3;
mySecondFavoriteNumber += 10  
/* will take the current value of the variable (which was number 3) and add up the value 10 to it which will result in 13 */

/* So by using += sign we're actualy taking the current value of a variable and we add a new value to it, instead of just replacing it. The second example could be written like this aswell, if it's a bit easier to understand: */

mySecondFavoriteNumber = mySecondFavoriteNumber + 10;

Same thing applies to string values aswell; plus equal sign takes the current value of the variable and then add the other value at the end, instead of just replacing the previous value of a variable (it's a process known as concatenation, when combining more strings together).

var greetings = 'Hello';

greetings += ' world';

/* Which results in "Hello world" */

Hope that helps out = ). Cheers

Perfect. Thank you very very much.