Using the element collections.

Dynamic HTML exposes elements through collections on the document. For example, you have a forms collection containing the form elements, an image collection with image elements, and so on. In addition, Internet Explorer 4.0 and Netscape 6.0 have the all collection containing all the HTML elements in the document.

Since DHTML allows you to manipulate the page and its contents, these collections may need to recalculate and adjust themselves when accessed. To improve performance, you should try to minimize the access into these collections.

Length Property This is the way most loops enumerating elements are written:

for (var i = 0; i < document.all.length; i++) {
  // code
}

Everytime you call the length property, the elements in the collection may be recounted. Do this for each loop iteration and you can see how this may become expensive. Instead, a better approach is to set the value of the length equal to a variable and use it in the for loop:

var numElements = document.all.length
for (var i = 0; i < numElements; i++) {
  // code
}
Accessing Elements A similar issue exists for accessing elements within the collection, especially when done by it's name - it's key value (eg., document.forms["myForm"]). Each time you make such a reference, the element is looked up in the underlying collection. Following the same principle used above, you should set the element to a variable name before manipulating it:
var numElements = document.all.length
for (var i = 0; i < numElements; i++) {
  var el = document.all[i]
  // manipulate el
}

Taking this one step further, imagine you wrote a loop that enumerates all the forms in the page and all the elements in the form. Below is the non-optimized approach followed by a more efficient solution:

// Non-optimized
for (var f = 0; f < document.forms.length; f++) {
  for (var e = 0; e < document.forms[f].elements.length; e++) {
    // manipulate each element
  }
}

// Optimized
var numForms = document.forms.length
for (var f = 0; f < numForms; f++) {
  var formElements = document.forms[f].elements
  var numElements = formElements.length
  for (var e = 0; e < numElements; e++) {
    var el = formElements[e]
    // manipulate each element, el
  }
}

Notice how we were careful to cache references to the form's elements, and then to each element. Doing this greatly minimizes how many accesses you need to make to each collection. Keep in mind there are scenarios where these optimizations may be bad coding. For example, if in your loops or code you are manipulating the document in ways that may change the number of elements or whether an element is still available, caching these values can cause problems.