Sep 29, 2009

The Document Object Model

We used PHP to retrieve information from web pages last week. But there are other methods, which appear interesting. One such method is the Document Object Model standard. The DOM provides the information needed for Javascript to communicate with the elements on the web page. The DOM itself isn't Javascript. It's a standard from the World Wide Web Consortium that most browser manufactures have adopted and add to their browsers.

The Document Object Model is the representation of the way the web browser remembers the HTML tags, their attributes and the order in which they appear in the file. There are two methods for selecting nodes. Nodes are the tags, tag attributes, and text of the web page. The two main methods for selecting nodes are:
getElementById() and getElementByTagName()

Getting an element by ID means locating a single node that has a unique ID applied to it. We would use the following Javascript to select the node:

document.getElementById('header')

We can also use a variable instead of a string such as:

var lookfor = 'header';
var foundNode = document.getElementById(lookfor);

When we assign the result of this method to a variable, it allows us to store a reference to a particular tag so that we can later manipulate it in our program. The getElementById() command returns a reference to a single node. The getElementByTagName () command is used to retrieve multiple items.

For example, to retrieve all the links on a page, you could do something like:

var pageLinks = document.getElementByTagName('a');

The varaible “pageLinks “ would store all the links from the selected page in same matter as a array. Therefore pageLinks[0] would be the first link from the selected page.

Beyond the methods I mentioned moving around a page using the DOM method becomes difficult and time consuming. Each browser interprets the DOM differently. Javascript makes using the DOM method almost a waste of time, because of the difficulty of getting the standard to function correctly with all the available browsers.

1 comment:

  1. I heard Dr. Drake say that we have actually been using DOM in our JavaScript even though he hasn't discussed it. I don't understand it completely but this post helps to describe it better.

    ReplyDelete