However, the DOM functions allow us to push information into the document in a more structured manner, making it much more likely that the browser will interpret it properly.
There are a handful of DOM functions we will explore in this tutorial. They are: createElement, createTextNode, appendChild, insertBefore, replaceChild and removeChild. This post will deal with the “createElement” function.
Let’s start with the createElement function. Basically, this function does exactly what it says. It creates an element to be inserted into the DOM. Initially, when creating an element, it doesn’t really go anywhere. It just kind of floats out there in cyberspace, until you tell the interpreter where to place that element inside of the DOM. That’s where the insertBefore, appendChild and replaceChild functions come in. We will explore those in a moment.
First, let’s look at some code that creates an element for us.
var myimg = document.createElement("img"); myimg.id = "myimg"; myimg.src = "test.gif"; myimg.alt = "This is a test image";
When setting attributes for your elements, you can set any attribute that’s allowed by the DTD. In the case of an XHTML file, the img tag can have any of a number of attributes (the full list can be found in the img tag definition on w3schools). In the case of an XML file, you would have to consult the DTD in order to know which attributes are legal. However, there is a slightly different way of setting attributes when working with an XML file (which we won’t discuss at this juncture, since we are dealing strictly with XHTML for the purposes of this tutorial).
In the next installment, we will begin exploring how to add your new element into the DOM.