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,147
  • 12
  • 54
  • 58
Simon
  • 13
  • 3

2 Answers2

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/

Musa
  • 96,336
  • 17
  • 118
  • 137
  • 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 :) – Simon May 13 '13 at 00:16
-1

getElementById returns a single element and not a collection.

the correct code is:

document.getElementById('TestID').style.background = '#f00';
monokh
  • 1,970
  • 3
  • 22
  • 31