[Javascript] Fw: hide other divs

Paul Novitski paul at juniperwebcraft.com
Wed Apr 12 04:12:50 CDT 2006


At 01:43 AM 4/12/2006, Michael Borchers wrote:
>  var divElements = document.getElementsByTagName("div");
>
>     for(i=0;i<divElements.length;i++)
>  {
>         divElementsId = divElements[i].getAttribute("id");
>
>   if(divElementsId.substring(0,6) == mySubstring && divElementsId != myDiv)
>   {
>    divElements[i].style.display = "none";
>         }
>     }
>}

Michael,

Yes, I believe your script is failing [in Firefox] because you're 
executing a string method on a null object for the first div that 
doesn't have an id.  You can fix this simply by adding a test for its 
existence to the beginning of your Boolean logic:

divElementsId = divElements[i].getAttribute("id");

         if (divElementsId
             && divElementsId.substring(0,6) == mySubstring
             && divElementsId != myDiv
         )

When the current element doesn't have an id, divElementsId will be 
NULL (== FALSE) and the if-test will break off correctly.

JavaScript (like PHP) will stop processing a complex IF-test 
expression as soon as its value is guaranteed.  Because you're only 
using Boolean AND (&&), any FALSE value among its components makes 
the whole value false.  When divElementsId is NULL (FALSE) then the 
entire expression will be FALSE, and JavaScript will never process 
the other terms of the expression and therefore won't fail on NULL.substring().

Paul




More information about the Javascript mailing list