spacer
Yehuda Shiran October 9, 2000
Looping via an Iterator
Tips: October 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

The Enumerator object provides the iterating mechanism you can find in other OOP languages. It supports four methods: atEnd(), item(), moveFirst(), and moveNext(). The following example shows four links to our four latest tips. These links, together with other links hidden in this tip, form a collection, document.links. We loop through the items in the collection with a for() loop. During each iteration we just pop an alert box with the link's URL. The four methods that the Enumerator object supports are exactly what we need for this for() loop:

  • We initialize the loop with the moveFirst() method.
  • We check for the loop termination with the atEnd() method.
  • We step forward in the loop with the moveNext() method.
  • We print the link's URL with the item() method.

This is the script that implements this loop:

linkEnum = new Enumerator(document.links);
  for (linkEnum.moveFirst(); !linkEnum.atEnd(); linkEnum.moveNext()) {
    alert(linkEnum.item());
  }

Here are the links and the button you need to click to invoke this script (the first four links are from somewhere else in this tip):

0010108 0010107 0010106 0010105

Here is the code for the links and the script that implements the function triggered by the button:

<A HREF="http://www.webreference.com/js/tips/001008.html">0010108</A>
<A HREF="http://www.webreference.com/js/tips/001007.html">0010107</A>
<A HREF="http://www.webreference.com/js/tips/001006.html">0010106</A>
<A HREF="http://www.webreference.com/js/tips/001005.html">0010105</A>
<FORM>
<INPUT TYPE="button" onclick=printLinks() value="Print Links">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
function printLinks() {
  linkEnum = new Enumerator(document.links);
  for (linkEnum.moveFirst(); !linkEnum.atEnd(); linkEnum.moveNext()) {
    alert(linkEnum.item());
  }
}
// -->
</SCRIPT>


People who read this tip also read these tips:

Look for similar tips by subject:


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger