Get the number of Images of a web page

R

Rob

I used the following code, but it didn't work.

var imgs = document.getElementsByTagName("img");
nimgs = imgs.length;
alert("A total images of: " + nimgs);
 
R

RobG

I used the following code, but it didn't work.

"Didn't work" is not much to go on. Was the value wrong? Did you get
an error? Did you get any response at all?

var imgs = document.getElementsByTagName("img");
nimgs = imgs.length;
alert("A total images of: " + nimgs);

The code is syntactically correct, however it will only report the
number of image elements in the document at the time that it is run.
If you haven't waited for the body element's load event to occur, it
is likely that the number will be wrong.

Also, there is a live images collection that can be used rather than
getElementsByTagName, so:

window.onload = function() {
alert("Number of images: " + document.images.length);
}
 
D

Dr J R Stockton

In comp.lang.javascript message <c2e85bcc-4f4f-430e-afdd-060a1a906ad2@s9
g2000prg.googlegroups.com>, Mon, 26 Jan 2009 14:08:21, Rob
I used the following code, but it didn't work.

var imgs = document.getElementsByTagName("img");
nimgs = imgs.length;
alert("A total images of: " + nimgs);

To be more helpful, you should say in which versions of which browsers
it was found not to work, and in what manner it failed. Since it works
for me in two simple tests in IE7 & FF3 & SF3 & Op9, the problem may lie
in your context.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.
 
E

Evertjan.

kangax wrote on 28 jan 2009 in comp.lang.javascript:
Don't forget that `imgs.length` will resolve to an actual image element
in MSHTML DOM if one of the elements in collection has id="length"


How terrible!!

var imgs = document.getElementsByTagName("img");
if (imgs.length.id) imgs.length.id = "howTerrible";
nimgs = imgs.length;
alert("A total images of: " + nimgs);
if (imgs.howTerrible) imgs.howTerrible.id= "length";

Will this help?

Not tested, I want a quiet eavening.
 
R

RobG

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? :)
 
R

RobG

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? :)

Just for the heck of it, here's a simple one:

function countElements(tag) {
var col = document.getElementsByTagName(tag);

// Set the index to start searching from and the
// initial increment.
// The initial values should be [0, 1] but since the
// loop requires the parameters to be adjusted, the
// initial values are modified so the correct values
// are passed in the first call after adjustment.
var p = [2, 2];

function goForward(i, inc) {
while (col) {
i += inc;
inc *= 2;
}
return [i, (inc/2)];
}

while (p[1] > 1) {
p = goForward( p[0] - p[1], p[1]/2 );
}

return p[0];
}

It takes 43 loops to count a collection of 2,371 elements (a prime
number) in less than 20ms in IE 7 and Firefox 3 on a modest machine.
The loop can be optimised a little further (e.g. test if element[i+1]
exists before calling goForward), but trimming a couple of loops isn't
likely to gain much.

After the first call to getElementsById, the result seems to be cached
and subsequent calls to the function take zero time (using the
traditional new Date method to measure elapsed time), so probably the
greatest amount of work is the call to getElementsById. Optimising
the actual loop further is pointless.
 
R

Richard Cornford

Don't forget that `imgs.length` will resolve to an actual
image element in MSHTML DOM if one of the elements in
collection has id="length"

I can understand someone giving a form control the name "length" (if
the value it held was in some sense a length, or even something like
"fileSize" if the size of a file was related to its purpose), but
giving an IMG element the ID "length" would stupid. Sensibly the value
of IDs should say something about the purpose they are being used for,
which becomes saying something about the element they are applied to,
or the purpose of that element.

There really is no point in jumping through hoops in order to
accommodate the very stupid. For a start, once you start down that
road there is no end in sight as the capacity for stupidity in humans
far exceeds anyone's ability to anticipate it.

There was a recent thread in a JQurey group where someone was
complaining that JQuery could not retrieve 'nested' FORM elements
using the appropriate CSS selector. Of course it could not as
regardless of the possibility of writing mark-up that nests the
elements, HTML and the DOM do not allow FORMs inside FORMs. However,
at the expense of massive code bloat, JQuery could accommodate that
mistake, and the individual asking the question would probably be
happy if they did. But maybe the best approach is just to show the
people who aren't willing to put any thought at all into what they are
doing the door.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top