Monday, May 23, 2005

Object Detection (JavaScript)

Object detection is a better way of writing JavaScript as the DOM cannot be faked like the user agent. Scripting Methods has a useful reference of DOM objects and what browser they are implemented in. It is also means forwards compatibility is less of an issue.

So for instance, to get an element on a page (works in IE4+ and most modern browsers) :

var myelement;
if (document.getElementById) {
  myelement = document.getElementById("myelement");
} else if (document.all) {
  myelement = document.all["myelement"];
}
if (myelement) {
  // do something
}

Tags: , ,

No comments: