[Javascript] javascript and id's

Paul Novitski paul at novitskisoftware.com
Tue Oct 4 14:06:06 CDT 2005


At 11:20 AM 10/4/2005, Anthony Ettinger wrote:
>--- Paul Novitski <paul at novitskisoftware.com> wrote:
> > I would argue for a safer coding practice:
> >
> >          var oEl = document.getElementById(id);
> >                  if (oEl) oEl.setAttribute(attrib,
> > newValue);
> >
> > ...in order to avoid a javascript error message if
> > the expected
> > element doesn't exist on the page.
> >
>
>Great. So you recommend testing for getElementById
>first, good idea.

Anthony,

Well, no, actually, I wasn't testing for the getElementById() 
capability, I was testing for the existence of the identified element 
(id) on the page.

It might seem twitchy if not downright neurotically fussy to test for 
the existence of a page element that you yourself are placing in the 
markup, but the history of software development is littered with the 
bodies of dead code that won't run because the programmers made one 
too many assumptions about the predictability of future contexts...

I do test for DOM capability, but I only do so once:

None of my javascript functions are triggered directly from the HTML 
file (I don't use inline behavior in the markup like <tag 
onclick="doSomething()">).  Instead, my linked javascript file 
contains a window.onload statement that runs an initialization 
function; that function assigns behaviors as needed to various page elements.

In this way, no javascript is executed unless the initialization 
function completes. If the init function begins by testing for the 
DOM capabilities it requires, effectively all subroutines are 
protected from being run by non-DOM-aware browsers, so there's no 
need to keep testing for DOM capability anywhere else.

function Initialize()
{
         if (!document.getElementById) return;
         if (!document.getElementsByTagName) return;
         // etc.
}


>Would you bother with an else in that statement? Or
>simply break it. I personally don't care to support
>older versions of IE and NS. Accessible means screen
>readers, mobile devices, etc. ANY javascript would
>break on those.

If an expected page element doesn't exist, or a browser lacks DOM 
capability, I suppose you could bring up an alert() notifying the 
user if the lacking functionality is critical.  In most cases I 
simply end silently if running in a DOM-unaware browser.  Missing 
page elements are more troublesome and might indicate that someone 
has made a mistake in editing the markup or that the script is being 
run with an inappropriate page, and therefore might deserve a warning 
message so the user can notify the developer.

Paul 




More information about the Javascript mailing list