www.webdeveloper.com
Results 1 to 8 of 8

Thread: getElementById() isn't working

  1. #1
    Join Date
    Aug 2009
    Posts
    4

    Question getElementById() isn't working

    So basically I have this code:

    Javascript:
    Code:
    var virtualbag = document.getElementById('VirtualBagImage');
    HTML:
    Code:
    <img id="VirtualBagImage" src="virtualbag.php?bag=1&fabric=75&trim=24&hardware=6&width=150" />
    The goal is to be able to change the source with virtualbag.src = somethingelse; but if I do this the script stops executing (and of course, javascript never gives any error message).
    alert(virtualbag); says "null".

    I'm hoping I'm just missing something obvious.. I don't have much experience with javascript but I don't understand what's wrong.

    Thanks for any help.

  2. #2
    Join Date
    Aug 2008
    Posts
    36
    that dosen't look like an image URL...

  3. #3
    Join Date
    Aug 2008
    Posts
    36
    and you can't put images in alerts.

  4. #4
    Join Date
    Aug 2009
    Posts
    4
    php can generate images (a png in this case). The image actually works perfectly, I just can't change it.

    I used the alert to see if it's finding anything, getElementById() is supposed to return null if it can't find anything. I assume it would give something different if it found it. The main thing is that virtualbag.src = newurl; doesn't work.

  5. #5
    Join Date
    Oct 2008
    Location
    U.S.
    Posts
    726
    Are you trying to access the image before the window has fully loaded?? Try:
    Code:
    window.onload = function () {
        var virtualbag = document.getElementById("VirtualBagImage");
        if (virtualbag !== null) {
            alert(virtualbag.src);
            //virtualbag.src = //insert your path or variable here
        } else {
            alert("can't find VirtualBagImage! Id must be wrong!");
        }
    };

  6. #6
    Join Date
    Aug 2009
    Posts
    4
    Tried this.. It gives the error message ("can't find VirtualBagImage..")

  7. #7
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    You only have one id with that value right?
    Do you have any thing with the same name?

    You are 100% positive the spelling is right.

    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint] | twitter | linkedin | http://www.pascarello.com

  8. #8
    Join Date
    Aug 2009
    Posts
    4
    Oh hey actually that fixed it. I just didn't test it right. Thanks a lot I just needed it to run after the page loaded..

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles