/    Sign up×
Community /Pin to ProfileBookmark

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

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@xelawhoOct 08.2012 — 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
Copy linkTweet thisAlerts:
@markimarkcauthorOct 08.2012 — 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
Copy linkTweet thisAlerts:
@xelawhoOct 08.2012 — try initializing your array like this:
[CODE]
var array=[];
[/CODE]


(and a quicker way to define it is like this):
[CODE]
var array=['button_background', 'button_menu','button_faq']
[/CODE]
Copy linkTweet thisAlerts:
@markimarkcauthorOct 08.2012 — 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
×

Success!

Help @markimarkc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...