HTML and CSS Reference
In-Depth Information
Decision Making: Supporting Different Document Object Models
One challenge facing JavaScript programmers is to support a wide range of document
object models. The most powerful and flexible at the time of this writing is the DOM based
on HTML5, but that DOM isn't supported by browsers that are only a few years old. One
way of dealing with this problem is to write your code to the most common standard. This
is not easy to do with versions of Internet Explorer before IE6 because those browsers sup-
ported the IE DOM, which differed in many important ways from the W3C DOM.
The most common approach is to use object detection in which an object reference is
tested before being used in the program code. Object detection uses the if structure
if ( object ) {
where object is a JavaScript reference to an object. If the browser supports the object ref-
erence, it runs the command block; otherwise, the command block is skipped. For example,
the following statement uses object detection to verify that the browser supports the
document.getElementsByClassName() method from the HTML5 DOM:
if (document.getElementsByClassName) {
commands for the HTML5 DOM ;
} else {
commands for other DOMs
If the browser doesn't support this method, it instead runs commands that do not assume
support for the HTML5 DOM.
Object detection is an important tool for JavaScript programmers that should be used
whenever there is a question about the support for an object, property, or method.
Writing Event Handlers as Object Properties
To run the init() function, you added an event handler attribute to the <body> tag in the
HTML file. However, any document object can be assigned an event handler from within
your JavaScript program using the expression
object .on event = function ;
where object is an object in your Web page document or browser, event is the name
of the event, and function is the name of a function to be run in response to that event.
For example, to run the init() function when the page is initially loaded into the browser
window, you could run the following JavaScript command:
Do not include the paren-
theses () when specify-
ing the event handler
function; include only the
function name.
window.onload = init;
Search WWH ::

Custom Search