[Javascript] IE work-a-round question (re: checkboxes)

Paul Novitski paul at juniperwebcraft.com
Sat Apr 12 09:36:42 CDT 2008


At 4/12/2008 06:56 AM, tedd wrote:
>     Error: 'document.getElementById(...) is null or not an object.
>
>The offending code is this:
>
>function HideTimedLayer(id)
>     {
>     document.getElementById(id).style.display = "none";
>     var id2 = 'c' + id[2] + id[3];
>     document.getElementById(id2).checked = true;
>     }


Tedd, your code above (...id[2] + id[3]...) indicates that the 
variable id is an ARRAY.  getElementById() takes a STRING as its argument.

Paul
_______________________

[sent earlier but didn't appear on the list:]


At 4/11/2008 01:56 PM, tedd wrote:
>document.getElementById(id).checked = true;


Yeah, checked isn't a native DOM element property.  Use setAttribute.
http://developer.mozilla.org/en/docs/DOM:element#Properties
http://developer.mozilla.org/en/docs/DOM:element.setAttribute

Tangentially, I've gotten into the habit of keeping statements 'atomic':

                 if (!typeof(id) == 'string')
                 {
                         debugAlert('id is not a string');
                         return false;
                 }

         var oObj = document.getElementById(id);
                 if (!oObj)
                 {
                         debugAlert('Cannot find ' + id);
                         return false;
                 }

         Obj.setAttribute('checked', true);
         ...

If one component of a compound statement throws an error it can be 
difficult to debug.  Yes, it is more verbose, but a) computers these 
days are very fast and JavaScript execution speed is almost never an 
issue and b) if splitting the compound statement into separate atomic 
statements makes it easier to catch run-time and compile errors, it 
has time-saving value for you the programmer and useability value for 
the visitor who is less likely to have JavaScript halt or bomb out.

Of course I keep to a middle ground; I'm not afraid to combine some 
functionality such as a function call and text concatenation in one 
statement as above.  The example you provided is particularly 
vulnerable because the overall statement (element.property = value) 
fails if getElementById(id) returns a null object when id is not 
found or if the property does not exist, but with no indicator of 
which component failed.  The opaqueness of the error is evident by 
your suspicion that getElementById() isn't supported by IE, whereas I 
think it was 'checked' that killed the beast.

Regards,
Paul  




More information about the Javascript mailing list