Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Ajax and JavaScript

Like this article? We recommend  Adding the Image Element to the Page

Adding the Image Element to the Page

Next, we need to "get" the div element into which the image element goes. This is easy, as the div has an ID, and we can use the getElementById method to get it:

var theDiv=document.getElementById("display");

Now we have the div as an object, and we can add a child object to it. A child object of an element is nested inside of the parent element's opening and closing tag, which is exactly where we want our new image element to go. The appendChild method takes one argumentβ€”the element to add, which we're holding ready to go in the myImgEl variable:

theDiv.appendChild(myImgEl);

When the code runs, the new image element will be inserted into the div, and this will cause the randomly selected image to be displayed.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.