DOM using Javascript

[OBSOLETE] Please use the JQuery library to achieve cross-browser DOM manipulation (and more!)

The DOM (Document Object Model) allows us to represent a HTML page as a tree-like structure. With the increased use of Javascript and new concepts such as AJAX, DOM has become a rather important model. Without good knowledge of the DOM, you may find yourself in a fix when trying to even manipulate the simplest elements.

I assume you have intermediate knowledge of HTML and Javascript, for they are essential in manipulating the DOM. Simple knowledegde of XML may also help, since DOM is actually a method for processing XML. This tutorial does not compare between DOM and SAX, but simply focuses on DOM. This tutorial is not meant to solve a particular problem, but to increase your knowledge of the DOM so that you can work with it better. If you don’t have these prerequisites I suggest you brush up your skills before coming back, or just treat this as a bedtime story.

The methods here have been tested in Internet Explorer and Mozilla Firefox. Despite browsers having their own “extensions” to DOM and Javascript, they attempt to comply with the World Wide Web Consortium (W3C) DOM standard. By using methods belonging to the standard, you can omit ugly browser detection code. It is still recommended that you test the scripts in your target environment to see if the browser supports these features. Do feedback if there is a simple and better cross-browser method.

Jump to a specific topic:

  1. The HTML Page
  2. Essential DOM Method: getElementById()
  3. DOM Debugging
  4. Common Attributes and Methods
  5. Common Styles
  6. Form Manipulation
  7. Table Manipulation

The HTML Page

We start by first examining a HTML page.

      <title>Hello World!</title>
      <h1 id="hello">Hello <i>World</i></h1>
      <p id="goodbye" align="right">Goodbye!</p>

So what can we see from this simple page? When the page is parsed into a DOM tree, it will have a hierarchy like this:

 + html
   +-+ head
   |   |
   |   +-+ title
   |       |
   |       +-- "Hello World!"
   +-+ body
       +-+ h1 (id=hello)
       |   |
       |   +-- "Hello "
       |   |
       |   +-+ i
       |       |
       |       +-- "World"
       +-+ p (id=goodbye, align=right)
           +-- "Goodbye!"

We introduce a few DOM terms here. Every item you see on that tree is known as a Node. There are 2 types of nodes, Text Node and Element Node.

Text nodes contains text literals, just like those strings above in quotes. They are the innermost nodes and cannot contain other nodes nor formatting. (if the text has formatting it would have been in another element node such as <i>).

Element Nodes represent each tag you place in angle brackets <>. Each element node has