Jump to content

FOR loops using i<array.length


barryg

Recommended Posts

This works fine (got it from the site tutorial, in fact):<CODE><script type="text/javascript">var i=0;for (i=0;i<=5;i++){document.write("The number is " + i);document.write("<br />");}</script></CODE>But when I try to set the upper limit of the loop to the allTags array (and I'm getting this from a Lynda.com class, entitled Essential Javascript), it fails:<CODE><html><body><script type="text/javascript">var i=0;var allTags = document.getElementsByTagName("*");for (i=0;i<allTags.length;i++){document.write("The number is " + i);document.write("<br />");}</script></body></html></CODE>It writes the phrase to the screen this many times:The number is 0. . . . . . .>>>>on and on and on to<<<<<<The number is 414765 and it only stops then because it choked my browser.What's up with this? I know there aren't that many tags on ANY page (well, almost any page), so where is it getting this bizarre length?If I set the tag name to "p," and add three paragraphs, It fails to work at all. If I set the tag to "body" or "script," it cycles once, as expected.So. . .how is the getElementsByTagName() supposed to work, especially with the "*" character and the "p" character.Any help would be appreciated, although I am sure this simple stuff for most of the members of this forum.Barry

Link to comment
Share on other sites

I suspect that the fact that you're using document.write to add a new <br> tag every time has something to do with it. Try this:

<script type="text/javascript">var i=0;output = '';var allTags = document.getElementsByTagName("*");for (i=0;i<allTags.length;i++){  output += "The number is " + i + "<br />";}document.write(output);</script>

That way it only gives output once the code is finished. Also, if you're going to put that script in the body then make sure it's last, any other markup should go before it.

Link to comment
Share on other sites

The point is, getElementsByTagName does NOT return an array. It returns a DYNAMIC collection. The contents are updated automatically as the DOM changes. You code changes the DOM, so it changes the collection.

Link to comment
Share on other sites

The point is, getElementsByTagName does NOT return an array. It returns a DYNAMIC collection. The contents are updated automatically as the DOM changes. You code changes the DOM, so it changes the collection.
You learn something new every day... :)
Link to comment
Share on other sites

If anyone is interested in testing the concept, start with an empty <body> element and execute this code:

var els = document.body.getElementsByTagName("*");for (var i = 0; i < 10; ++i) {   document.body.innerHTML += "<span>" + els.length + ", </span>";}

The extra comma at the end spoils the effect a little, but I wanted to keep it simple.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...