I would probably do a stronger test (although still quite naive), but
I'm not sure it's *really* necessary here:
An alternative is to use a method where it doesn't really matter if
the test is deficient (i.e. gets some false positives) and uses an
independent method to determine the number of items in the collection,
e.g.:
function countElements(tag) {
var elCollection = document.getElementsByTagName(tag);
var numItems = elCollection.length;
if (typeof numItems != 'number') {
var i = 0;
while (elCollection[i++]) {}
numItems = --i;
}
return numItems;
}
Works in IE 7 at least, and should be quick enough.
The above approach is appealing because it directly tests if length
returns a number and makes no assumptions if it doesn't. If the test
fails, it just loops through the collection and counts how many items
there are. Note that this is an issue for IE for any collection where
one of the elements has an ID of length.
If it is to be used for a large collection, a b-tree type algorithm
could be used so you can count to say 1,000,000 in about 20 loops, so
performance is not an issue. I'm sure the bit-wise shift operator can
be used to great effect here - Dr J?