Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    May 2007
    Posts
    34
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Changing image in a div without id

    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!

    Code:
    <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
    If you have nothing good to say about someone, say nothing at all!

  • #2
    Supreme Master coder! _Aerospace_Eng_'s Avatar
    Join Date
    Dec 2004
    Location
    In a place far, far away...
    Posts
    19,291
    Thanks
    2
    Thanked 1,043 Times in 1,019 Posts
    Code:
    function changeImage(o,what) {
    	o.getElementsByTagName('img')[0].src = what;
    }
    Try that.
    The correct syntax for your previous code should have been
    Code:
    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
    Code:
    <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.
    Last edited by _Aerospace_Eng_; 06-11-2007 at 04:05 AM.
    ||||If you are getting paid to do a job, don't ask for help on it!||||

  • #3
    Senior Coder
    Join Date
    Aug 2002
    Location
    UK
    Posts
    2,789
    Thanks
    2
    Thanked 14 Times in 14 Posts
    You should be able to do it something like this as well

    Code:
    <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>
    The silent one.

    The most dangerous thing in the world is an idea.
    The most dangerous person in the world is the one with an idea.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •