How to test for the Javascript DOM?

Written by Riaan Pieterse

Browsingrepparttar forums, development articles and other resource sites raised an interesting yet recurring question: "How do I test forrepparttar 105593 Document Object Model (DOM) employed by a browser?". Strangely enough I was askingrepparttar 105594 same question when starting out in Javascript. However, after enough time has passed, withrepparttar 105595 same thing done more than once, I started to realise that this is a question that begs answering for once and for all.

A Typical Test

Testing forrepparttar 105596 DOM in itself is easy enough. A recommended approach is testing forrepparttar 105597 support of a DOM, and not for a browser version. The following describes Boolean variables that indicatesrepparttar 105598 compliance to repparttar 105599 DOM methods and parameters that you are targeting:

isIE4 = document.all? true : false;

isIE6 = document.getElementById && document.all ? true : false;

isNS4 = document.layers? true : false;

isNS6 = document.getElementById && !document.all ? true : false;

The above items return a set of true or false values for any browser. This method still requires that you access objects described byrepparttar 105600 DOM through that DOM's methods. Inrepparttar 105601 long runrepparttar 105602 amount of work you have to do remains more or lessrepparttar 105603 same.

Javasript is an Object Orientated language

Everyone who is familiar with Javascript knows thatrepparttar 105604 language supports Object Orientation (OO). Passing objects around in variables is nothing new, so why do people persist in performing lengthy tests forrepparttar 105605 DOM each time we need to access an object?

The item which describesrepparttar 105606 document's referencing structure is nothing more that an object itself. This means that you only need to performrepparttar 105607 test once, and then proceed to use an arbitrary object that describes repparttar 105608 DOM object throughoutrepparttar 105609 remainder of your script. However, since this approach would require that you define a variable for each and every object you will be referencing, we need an approach which is more robust.

A Compromise

Typically you access objects thoughrepparttar 105610 DOM for one of two reasons: Get a value, or Set a value. Previous approaches require that you access repparttar 105611 object throughrepparttar 105612 DOM methods each and every time you need to perform some action onrepparttar 105613 object. The same holds true for every other object accessed by your script. What we need is a method that will:

  1. Accessrepparttar 105614 correct DOM usingrepparttar 105615 relevant methods
  2. Returnrepparttar 105616 object of interest
  3. Not waste time and patience

A practical approach used by myself is described in a function that returns your object without any hassles.

function getDOMObject (documentID){


Written by

Cont'd on page 2 ==> © 2005
Terms of Use