View Full Version : getElementById Puzzle

05-22-2009, 07:19 PM
I am using a function that accepts as input the object from getElementById like so:

which works if the element in question has id coded, like so:
<img id="test" src="cov1.jpg" width="263" height="338">

If I am in a situation where the element does not have id coded and I cannot change that, how can I chain through the img elements in the document, and what exactly do I have to pass to the changeIt function so that it will be same kind of object as document.getElementById('test')?


05-22-2009, 07:56 PM
for(var i = 0; i < document.images.length; i++){

05-25-2009, 07:24 AM
Thanks very much, Venegal... However, I only want to invoke the changeIt function for that one specific image. So as I run the chain of images, is there a way to access the file name so I know which image in the document to run the changeIt function on?


05-25-2009, 12:34 PM
You mean you want to changeIt a particular <img> which you can only identify by its src?

for(var i = 0; i < document.images.length; i++){
if (document.images[i].src == 'cov1.jpg') changeIt(document.images[i]);

05-25-2009, 02:01 PM
Yes, I'm afraid so. It is a site where I can add some javascript logic, but I cannot change the page markup, which is built by server side logic. The img is contained within a div like so:
<div class="img_1">
<a id="image1" href="whatever">
<img src="cov1.jpg" width="263" height="338" title="image1"></a>


05-25-2009, 02:46 PM
Well did you try the code I gave you in my last post?

Old Pedant
05-26-2009, 01:52 AM
Venegal's code works, but you could also do this:

var anchor = document.getElementById("image1");
var image = anchor.getElementsByTagName("img")[0]; // first image in the <a>...</a>

As long as you have *some* surrounding element with an ID, finding a sub-element via its tag name can be done that way.

SO you *could* do

changeIt( document.getElementById("image1").getElementsByTagName("img")[0] );

05-26-2009, 03:50 AM
yes, venegal, that worked nicely -- thanks so much!

Old Pedant -- Thanks, your approach is the specific solution I needed. Thanks both of you for all the help!