Creating custom collections in the DOM (via ID attribute)

Browsers that support DOM Level 2 such as IE6 and Firefox have a few methods for retrieving elements on the page. The two most prominent ones are:


whereby the first method retrieves an element with a specific ID, and the second fetches all elements of a particular TAG. But what if you want to collect arbitrary elements on the page to perform manipulation on them, such as 2 DIVs and 3 Paragraphs?. In IE6+, such a task can be accomplished by assigning the same ID to the elements you wish extracted, and then using document.all to retrieve them:

<img src="1.gif" id="test">
<span id="test">There</span>

<script type="text/javascript">
document.all.test.length //returns 2
document.all.test[0]   //returns <img src="1.gif">

This is a very simple way to create custom collections in IE. However, it does violate one of the unforgiveable sins of the DOM, by giving two or more elements the same ID value. The DOM specifies that the ID attribute should contain a unique value for each element that uses it. And of course, this method for creating custom collections only works in IE, not Firefox.

Creating custom collections using of the ID attribute

Here's the proper, cross browser way to create custom collections of using the ID attribute of the desired elements. It's more curcumsome than IE's proprietary model, but it's what DOM 2 offers us at the moment.

Here's the basic idea. In DOM 2 we can retrieve a specific element via document.getElementById. A custom collection is merely an assembly of such unique elements. So far so good? By labeling participating elements (via the ID attribute) in a particular manner, along with document.getElementById and a while loop, we have all the ingredients needed to retrieve arbitrary elements and store them into a custom collection.

Let's see just what all this means, in code:

<img src="1.gif" id="test0">
<span id="test1">There</span>

var i=0
var customcollect=new Array()
while (document.getElementById("test"+i)!=null){
customcollect[i]= document.getElementById("test"+i)

Notice how we labeled the participating elements- with an identical name suffixed with an incrementing number (ie: test0, test1). This is to facilitate the while loop that follows, which generically gathers these elements all up and into an array. Customcollect[] now contains what we want.

The above technique works in any browser that supports DOM 2, which are IE5+ and NS6+, Firefox etc.