www.webdeveloper.com
Results 1 to 5 of 5

Thread: Using an array to reference an HTML element

  1. #1
    Join Date
    Jan 2007
    Posts
    4

    Using an array to reference an HTML element

    Hi
    I am trying to create an array in a javascript function which will hold some button elements in HTML, so that I can loop them in Javascript.

    I can't get the below code to work:

    function buttonclick() {

    var array = ()
    array[0]='button_background';
    array[1]='button_menu';
    array[2]='button_faq';
    y = array[0]
    y.style.backgroundColor="#cc00cc";

    This obviously isn't the complete code...no loop etc. But I am just struggling to get the correct syntax for the above.

    Any help would be really greatly appreciated.

    Many Thanks

  2. #2
    Join Date
    Nov 2010
    Posts
    1,031
    are 'button_background', 'button_menu' and 'button_faq' supposed to be IDs? because it would be better referring to them that way if they are:
    document.getElementById(array[0]).style.backgroundColor="#cc00cc";

    etc

  3. #3
    Join Date
    Jan 2007
    Posts
    4
    Hi xelawho

    Many thanks for your reply to my problem. They are ID's. I now have this :

    function buttonclick(id) {
    var array = ()
    array[0]='button_background';
    array[1]='button_menu';
    array[2]='button_faq';
    document.getElementById(array[0]).style.backgroundColor="#000000";

    However, this is still not changing the background colour.
    I'm sure it must be something simple I am missing

  4. #4
    Join Date
    Nov 2010
    Posts
    1,031
    try initializing your array like this:
    Code:
    var array=[];
    (and a quicker way to define it is like this):
    Code:
    var array=['button_background', 'button_menu','button_faq']

  5. #5
    Join Date
    Jan 2007
    Posts
    4
    You Sir...are a genius...
    Thank you so much. It works a treat.
    I knew it must be something small...but ut's been annoying me for the last 24 hours.

    Many many thanks once again

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