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.


  
    
      Hello World!
    
    
      

Hello World

Goodbye!

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 ).

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

  • a type – which is its tag name, e.g. a node or a

    node.

  • subelements – are all nodes written within its tag, e.g. the

    node contains 2 subelements, the “Hello ” text node and the element node, which in turn contains 1 subelement which is the “World” text node. Note that nodes may have zero sub-elements. In the DOM world subelements are known as Child Nodes.

  • attributes – are properties of the node that describe the node itself, usually written within the start tag. For example, the

    node above contains the ‘id’ and ‘align’ attributes. If you’re familiar with HTML, you’ll be able to guess what attributes an element will contain, but do note that sometimes they fall under different names. If your first guess don’t work, check the reference.

  • methods – allow you to perform an action on the node object. For example, you may use table.insertRow() to create a new row, or use table.getChildNodes() to access the sub elements within the node.
  • style – is actually an attribute of the node, but it has been specially discussed because it is very common to adjust the look of an element using its style, and also its relation to cascading style sheets (CSS). In fact, the CSS style of the node can be reflected through this property.
    • Once you understand the structure of the DOM tree, we’ll start to explore how you can use Javascript to access and manipulate the DOM, as well as common attributes, methods and styles. We’ll also focus on form elements, which are common targets of DOM manipulation.

      Essential DOM Method: getElementById()

      To start working with DOM you need to to first obtain a reference to one of the nodes. One method is to navigate through the tree from the root to your desired node, but it is often tedious since most HTML files we work with are mostly generated and many times larger than the example above.

      Therefore the most common method is to label your node with an ID, and use the getElementById method to locate your node.

      
        
      

      The document variable is a global Javascript variable that gives you access to the HTML document. Here we locate the node with the ID “hello”, and store it inside the helloNode variable. If we run this script within the HTML file we created above, this node represents the

      node with the word “Hello “, and a child node . We prove this by inspecting the node.

      
        
      

      From this sample we learn a few properties that are common to most element nodes. The nodeName property tells you what kind of tag it is (which you should already know). Each element node also has a childNodes array, which contains all its sub elements. Using the length property of the childNodes array you can drill into the node using a loop or otherwise.

      DOM Debugging

      A side note about DOM programming is the use of the alert command to quickly debug your code, as shown in the previous example. Using alert like above allows you to inspect your variables to make sure they contain values they should contain, or what the value is if it’s wrong. Also since Javascript will run your code until it hits an error, I often use the alert to check which piece of code has been run. For example:

      
        
      

      When run, this code meets with an error before the alert. After I shift the alert one line up and re-run the code, the alert appears before the error occurs. This allows me to zoom into the offending line. You may argue that using a browser such as FF’s Javascript Console directly shows the offending line without the use of an alert. That is true, but when writing cross-browser code, the script might run fine in FF, but encounters an error in IE. In that case you’ll be stuck a misleading line number, or Line 0… This approach works irregardless of the browser you are testing on.

      The alert method “fails” under some circumstances, especially in big loops and timer events. I often go into a big loop or a repeat timer event with the alert popping up everytime I close it, forcing me to crash the browser. When debugging such code I use an alternative, which involves setting up a display on the page.

      
        
        
      

      Supposedly a timer event continuously add/removes items from the helloNode. If using an alert, you be stuck with the alerts repeatedly popping up. But using this method, the value is fed into a text box (I usually place it at the top of the page). If you place the inspection code right after the code where you change the node inside the timer, you get a “real-time” value of the length of the node. You can use a similar concept and modify the “debug” element into a

      or