...

View Full Version : Changing image in a div without id



GCharb
06-11-2007, 02:43 AM
Hello all

I am looking for a way to change an img src in a div without calling for an id, I tried this code, seems okay to me but it does not work!


<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function changeImage(o) {
o.childNodes.img.src="image2.gif";
}
</script>
</head>
<body>
<div style="display:block" onClick="changeImage(this)">
<img src="image.gif">Some text
</div>
</body>
</html>

Anyone has a suggestion?

GCharb

_Aerospace_Eng_
06-11-2007, 03:02 AM
function changeImage(o,what) {
o.getElementsByTagName('img')[0].src = what;
}
Try that.
The correct syntax for your previous code should have been

function changeImage(o) {
o.childNodes[0].src = "image2.gif";
}
However line breaks and spaces count as text nodes so the first node was not the image. It was the new line character.
If your html looked like this

<div style="display:block" onClick="changeImage(this,'codingavi.gif')"><img src="image.gif" alt="">Some text</div>

Then the second code in this post would work.

Mr J
06-11-2007, 02:02 PM
You should be able to do it something like this as well


<html>
<head>
<title>Untitled</title>

<script type="text/javascript">
function changeImage(o) {
o.getElementsByTagName("IMG")[0].src="image2.gif";
}
</script>

</head>
<body>

<div style="display:block" onClick="changeImage(this)">
<img src="image1.gif">Some text
</div>

</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum