1

I recently tried to re-use a (working!) javascript function and detected a strange behaviour: After a certain if statement within a for-loop the function stopps. I don't see any reason.

If a change the actual if condition to "1==1", it all works fine. But with the code being as above I get the first alert ('here we go') but I never get the second alert. So, the problem can't be connected witht the loop (being endless or something like that). But other than that I'm absolutely confused and helpless. (Tested with Firefox 26 and Internet Explorer 11)

<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript">
          function my_function(number_of_divs)
           {
             for (var k = 0; k <= number_of_divs; k++)
               {
                var index = k;
                if (document.getElementsByName("text_levels")[index].style.display == 'block')
                 {
                  alert('Here we go');
                 } 
               }
              alert('This is never shown');
           }
         </script>
    </head>

    <body>
        <a href="javascript:void" onclick="my_function(1)">Click</a>
        <div name="text_levels" style="display:block">The content of a div element</div>
    </body>
</html>
2
  • Shouldn't that be '==='? Commented Jan 22, 2014 at 13:22
  • Have you tried stepping through it with a debugger like firebug for example? Commented Jan 22, 2014 at 13:23

3 Answers 3

3

Issue is you have only one elements with particular name and array indexing starts with zero so you stop at less than condition.

for (var k = 0; k < number_of_divs; k++)

because when it try to call with index=1 the following statement throw the error:

document.getElementsByName("text_levels")[index].style.display == 'block'

Here is working Demo

Sign up to request clarification or add additional context in comments.

Comments

1

The error console tells you what the problem is:

Uncaught TypeError: Cannot read property 'style' of undefined

You'll need to perform a bounds check inside your if statement:

var index = k, 
    levels = document.getElementsByName("text_levels"),
    levelLength = levels.length;

    if(index < levels.length && levels[index].style.display == 'block')
    {
        alert('Here we go');
    }

Comments

1

It is because of this line

k <= number_of_divs

It should have been

k < number_of_divs

Since there is only one text_levels, it will let the loop to access the second element (element at index 1), which is not there. So, it fails with an error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.