1

My problem is: (only as example, must not make sense overall):

// make a function and pass part of the statement as argument
function ExampleFunction( argument ) {
 document.getElementById('TestID')[0].style.argument = '#f00';
}
// then later onload
ExampleFunction( background );

I found out that it doesn't work this way, but I can't find out how it would be right. If someone could correct the example to send me on my way I would be very happy and thankful.

Hugo Dozois
8,49812 gold badges56 silver badges59 bronze badges
asked May 13, 2013 at 0:08
1

2 Answers 2

2

Firstly document.getElementById returns a single element (or null if no element is found), so not [0]. secondly if you want to reference a property dynamically use [] notation

// make a function and pass part of the statement as argument
function ExampleFunction( argument ) {
 document.getElementById('TestID').style[argument] = '#f00';
}
// then later onload
ExampleFunction( 'background' );

http://jsfiddle.net/HM3mu/

answered May 13, 2013 at 0:11
Sign up to request clarification or add additional context in comments.

1 Comment

ps i forgot the [0] from a different function i used to copy where it wasnt id´s. but thankyou anyway for correcting that too :)
-1

getElementById returns a single element and not a collection.

the correct code is:

document.getElementById('TestID').style.background = '#f00';
answered May 13, 2013 at 0:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.