Get image src using JavaScript

The very simple method in javascript to swap images of named imag tags

For example,

<img name=”image1″ src=”image.jpg” />
<script>document[“image1″].src=”image1.jpg”;</script>

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=”image.jpg” /></div>

The answer is possible, 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=”image1.jpg”;
</script>

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:

<script>
var div = document.getElementById(“namedDiv”);
var image = div.getElementsByTagName(“img”)[0];
image.src = “image1.jpg”;
</script>

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

<script>
document.getElementById(‘namedDiv’).getElementsByTagName(‘img’)[0].src = ‘image1.jpg’;
</script>

but that makes it a bit harder to debug when you make a mistake 😉

I hope this will be useful to you. Please post your comments here

Advertisements