Reputation: 10138
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"
Upvotes: 2
Views: 6183
Reputation:
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 :)
Upvotes: 0
Reputation: 35031
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 ;-)
Upvotes: 1
Reputation: 75794
Yes that follows, something like:
document.getElementById('namedDiv').getElementsByTagName('img')[0].src = 'mynewpath.jpg';
Upvotes: 4
Reputation: 24657
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>
Upvotes: 2