California Ajax Solutions Team

www.CalAST.com

DOM manipulation

Although not part of the acronym, Ajax makes extensive use of another web technique called DOM manipulation. DOM stands for Document Object Model, and describes the internal structure of the browser corresponding to the current web page. This brings up the question of what a web page really is, and there's no easy answer. We can definitely say what it is not - the HTML file delivered to the browser from the server. This is simply a script, or set of instructions that tell the browser how to build the web page. Using these instructions, the browser builds a tree-like structure internally.

From that tree-like structure, the browser displays something on the screen. This is really important to understand, because it is possible to change (manipulate) the tree at run time. When you do this, the display changes immediately. Of course, you have to be very careful to change the tree correctly, and the tree structure varies from browser to browser. Happily, there are relatively standard behaviors provided by functions to change the tree safely - if you know what you are doing. Changing the tree usually consists of deleting and adding nodes, many of which have to be created (in JavaScript) in response to something the user does.

Click on the button at right to watch DOM manipulation in action.

The DOM is defined by the W3C (World Wide Web Consortium) and the specification includes several levels of compliance, zero being the most primitive. Even at the most basic level, the DOM tree consists of nodes, which can be element (e.g., <body>), text, or attributes. The root of the tree is the HTML element node, and it has two children, HEAD and BODY. If you know how to read and write HTML, then you can see where this is going - every web page can be represented as a tree full of nodes, which can have 0, 1, or many children.

Mostly a web programmer will work with the element and text nodes. Attributes consist of name-value pairs. They are usually accessed via the setAttribute and getAttribute methods of the object representing an element. Let's consider the following statement:

<div id="tgt">Write stuff here.</div>

This will produce an element node for the DIV, a text node for the string "Write stuff here.", and an attribute node for the id. How these nodes are arranged in the tree may vary from browser to browser, but the text node will be a child of the element node. Eventually, the DIV element node may have many children, as more is added to it. If you add a paragraph to the DIV, then a P element node would be added as a child of the DIV node, and the text of that paragraph would be added as a child of the P node.

Next

DOM Demo