views:

423

answers:

4

So I know that it is easy enough to swap images of named img tags

<img name="image1" src="" />
<script>document["image1"].src="candybar.jpg";</script>

The problem is that I am being forced to use content server, and I can't name the image tag.

So If I name a Div tag that wraps the image can I use that to specify the image tag in question?

Something like..

<div id="namedDiv"><img src="" /></div>
<script>
     var imgDiv=document.getElementById['namedDiv'];
     imgDiv.$imgtag$.src="candybar.jpg";
</script>

So because I know the parent, and it only has 1 image tage within, i want to say "hey Div, give me your only child as an object"

+2  A: 

Every dom node have childNodes property which is an array of nodes. You can pick first one.

<script>
     var imgDiv=document.getElementById['namedDiv'];
     imgDiv.childNodes[0].src="candybar.jpg";
</script>
Eldar Djafarov
Weird, even though my html looks like; <div id="hidImgDiv" style="clear: both; display: none;"> <img src="TechForum.jpg" alt="NA" border="0"> </div>I had to use an index of 1. I wonder if the non-breaking space counts as a node? or if the index just starts at 1.
Eddie
yes - this is text node:)
Eldar Djafarov
in this case maybe it is better to use getElementsByTagName('img')[0] just to be sure
Eldar Djafarov
See NickFitz's answer, any text at all between the div and the img tags will count as a node
Ian Clelland
I concur - just asking for the first node isn't reliable at all.
annakata
+4  A: 

Yes that follows, something like:

document.getElementById('namedDiv').getElementsByTagName('img')[0].src = 'mynewpath.jpg';
annakata
+1  A: 

Depending on the markup and the browser, the <img> element may not be the only child. For example, if there is any whitespace such as a line break then many browsers other than IE will create a text node.

The easiest way is to use the getElementsByTagName method of the wrapper element, which returns a NodeList, and get the first element in that NodeList:

var div = document.getElementById("namedDiv");
var image = div.getElementsByTagName("img")[0];
image.src = "candybar.jpg";

You can shorten that if you don't mind making it slightly harder to follow:

document.getElementById("namedDiv").getElementsByTagName("img")[0].src = "candybar.jpg";

but that makes it a bit harder to debug when you make a mistake ;-)

NickFitz
A: 

why dont use css style and sprite for get the same resutl without javascript. ????

the idea: http://www.pixelovers.com/css-sprites-mejora-rendimiento-web-i-37249

I can explain it :)