The document object model is the standard way of interacting with the content of a web page.
Before we can start looking at how to use the document object model (or DOM) we need to consider how the DOM looks at a web page and the terminology used. It is also worth considering what access to the web page was available before the DOM was developed as these collections are still available and are used by many old scripts.
It is now time to start looking at how to use the DOM.
- The most common DOM call of all is getElementById().
- Theproperties available when you access a DOM element depends on the element and what attributes that the tag supports.
- One group of porperties accessible on almost all elements are styles.
- While not a part of the standard DOM the innerHTML property is supported by all popular browsers and priovides a simple way of replacing large sections of HTML all at once.
- A DOM nodelist is similar to an array except that it doesn't have all the methods an array has. There are a number of DOM calls that return a nodelist, the most commonly used being getElementsByTagName().
- Not all of the useful DOM calls were included in the original standard and so some such as getElementsByClassName() had to be constructed using JavaScript until such time as the browsers considered them useful enough to implement within the browser itself.
Once you have a basic understanding of how to use the appropriate calls to access the DOM it is time to look at how to actually interact further with the DOM to actually change what elements that the web page contains.
- The simplest of the DOM update calls is removeChild() which will delete an element from the DOM.
- You can also create elements using methods such as createElement() and createTextNode().
- Creating an element doesn't automatically add it to the DOM. To do that you need to use a method such as appendChild() or insertBefore().
- You could replace an element by removing it and then adding the updated version but is is easier to do it in one step using replaceChild().
- Where you want to update more than one element within the page all at once you may find the createDocumentFragment() method a useful way of holding all the elements you are creating before adding them to the page in one go.
- Tables have their own extended set of properties and methods that allow all of the component elements of a table to be accessed without needing to extract separate nodelists. These are the most efficient way of performing table processing in most browsers.
In addition to allowing you to interact with the elements within the web page, the DOM also provides ways of interacting with events in unobtrusive ways. Unfortunately this is one area where the JavaScript DOM event processing and the way the JScript DOM does it differ with JavaScript using event listeners and JScript using attachEvent(). We can however combine these together to produce cross browser event processors.
