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

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
From the author of Assembling the Image Element

Assembling the Image Element

Perhaps the coolest aspect of DOM scripting is being able to conjure up a brand-new HTML element and add it into the page, as we'll do now. All the DOM scripting methods belong to the built-in document object. Let's start by creating an image element:

var myImgEl = document.createElement("img");

This element now exists in memory as an object called myImgEl. We need to do a little more to it before we actually add it to the page—we have to add the src attribute with the image path we made, as well as the required descriptive alt attribute. We can't see the element until we add it to the page, so we just have to carry on, believing that we're doing this bit correctly. We set the two attributes as properties of the object—note the dots. The setAttribute method requires two arguments: the name of the attribute and its value:

myImgEl.setAttribute("src",mySrc);
myImgEl.setAttribute("alt","my old car");

Now the image element is good to go.

  • + Share This
  • 🔖 Save To Your Account