SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Resident Boozehound simontheak's Avatar
    Join Date
    Jun 2003
    Location
    _root.europe.uk.london
    Posts
    965
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Inserting custom variables into the DOM

    Hi there,

    I'm using the following code:

    HTML Code:
    document.pic+"new_pic"+.src=pics[currentPic]
    I'm hoping that it will resolve itself as the following:

    HTML Code:
    document.pic2.src=pics[currentPic]
    Needless to say, that the variable new_pic has the number 2 stored in it, but I keep getting JavaScript errors whenever I load up the page.

    I'd be REALLY grateful to anyone telling me just where I'm going wrong.

    Thanks very much,

  2. #2
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try using document.getElementById() instead to find elements in the DOM tree. Then you could do:

    document.getElementById( 'pic' + new_pic ).src = pics[currentPic];

  3. #3
    code ninja hamstu's Avatar
    Join Date
    Nov 2002
    Location
    Montréal, Canada
    Posts
    375
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Like wysiwyq said, using getElementById is the best choice in this situation.

    But to do what you were attempting, this should work:
    Code:
    document['pic' + new_pic].src = pics[currentPic];
    You have to use bracket ([ ]) syntax to evaluate variables like that.

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    document.pic2.src=pics[currentPic]
    You should never use that syntax anyway. The proper syntax is:

    document.images["imgName"].src


    With that syntax it is very easy to use variables to form the name of the image you want:

    var num = 2
    document.images["pic" + num].src


Bookmarks

Posting Permissions

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