January 2, 2000 - DOM Object Generation
January 2, 2000|
DOM Object Generation
Tips: January 2000
Yehuda Shiran, Ph.D.
createElementmethod creates a stand-alone element under the document object. This element is a single node that has neither children nor father, and is not related to any other existing document nodes. The only information attached to such a node is the HTML tag it represents, such as
<TABLE>. The HTML tag is the only parameter you need to specify when calling the
createElement. To create a
<FONT>tag element, for example, you would write:
newObject = document.createElement("FONT");
A classic exercise for demonstrating the
createElement method is to create an HTML table. It is popular for several reasons. First, the table includes quite a few different HTML tags. Then, the
TABLE construct is deeply nested (five levels of hierarchy). Last, there is a hidden tag in HTML tables that you need to create explicitly (
TBODY). All other HTML constructs do not have hidden tags. We have explained this feature in length in Column 40, The Document Object Model (DOM), Part I. Here is a script that will create all the different tags needed by a table:
tableObj = document.createElement("TABLE"); tbodyObj = document.createElement("TBODY"); trObj = document.createElement("TR"); tdObj = document.createElement("TD");
Notice again that these four nodes (
tdObj) are similar to four satellites in space. There is no connection (yet) or any other relationship between them. We'll show you later in this column how to connect between them and how to add them to document trees. The following script creates the above four tag nodes:
Run this script and see that the top level node (
bodyNode) does not have any children, and thus:
bodyNode.firstChild = undefined
Also notice from the Alert window that the return value from the createNode method is the new object itself.
Learn about more DOM methods in Column 44, The Document Object Model, Part 5.