views:

79

answers:

2

I'm having a problem with getElementbyId as follows:

<script type="text/javascript">
<!--
function show_links(locale) {

     var box = document.getElementById(locale);

     if(box.style.display == "none") { 
      box.style.display = "inline";
     } 
      else { 

      box.style.display = "none";
     }

    }
    //-->
</script>

<div class="link"><strong><a href="javascript:show_links(test);">Test</a></strong></div>
<div class="test"> Blah blah blah. This content comes and goes. </div>

So there you have the code. When I click the link "Test", it should hide the "blah blah blah text". When clicked again, it should show. However, I have an odd problem. I processed the code through a debugger, and it seems that the line var box = document.getElementById(locale); is not working correctly. box is being set to null. Can anyone theorize why?

A: 
javascript:show_links(test);

test is an unknown identifer. Where did you define it? Did you mean to feed a string?

<div class="test"> Blah blah blah. This content comes and goes. </div>

There is no element with an id of test in this line. Use the proper attribute id.

meder
+3  A: 

You have several problems. First the critical ones:

  1. The value you are passing to the show_links function is the variable test. This is equal to undefined so it isn't going to match anything.
  2. The element you are trying to find by its id doesn't have an id. It has only a class.

You need to give the element you are trying to match an id and pass a string instead of an undefined value.

Then the lesser issues.

  1. You are testing the inline display style property, but you aren't setting it by default. As a rule of thumb, it is better to twiddle the className property, and have your styles defined in a stylesheet.
  2. You are using a javascript pseudo-URI instead of progressive enhancement.
  3. You have comments wrapped around the inside of the script. At best, these are pointless.
  4. You are twiddling a div between inline and none, but the default display value for a div is block. There are reasons to have a div styled inline, but most of the time you should be using another element.
David Dorward
+1. Even disregarding the benefits of progressive enhancement, `javascript:` pseudo-URIs were broken and obsolete the day they were born and never, ever should ever be used in a page. Ever.
bobince