Can variables be used as dom elements?

I have multiple input fields on a form, each with a unique name. For example, to change the color I would do:

testForm.username.style.background = "yellow";

      

username

- input name, and testform

- form name

I want to do this: replace username

with a variable elem

so that when the function is called to change the background color, I don't need to have a separate function for each unique field. I'll just post the name elem

and this function will work for every field.

testForm.elem.style.background = "yellow";

      

My problem is that it doesn't work. For example, he passed elem

fine to the function, but he says that testForm.elem.style

- null

. For some reason, javascript doesn't like variables for the element names I am assuming?

+2


source to share


5 answers


var elem = 'username';
testForm[elem].style.background = 'yellow';

      



+5


source


try

testForm [elem].style.background = "yellow";

      

or



var elem = testForm.username
elem.style.background = "yellow";

      

in the first case it elem

contains the username, and in the second case it elem

points to the actual DOM element.

+1


source


The JavaScript object property (in this case, the username property of the testform object) can be accessed using the syntax object.property

or object["property"]

. Since the second form takes a string (as shown by double quotes), it follows that the variable containing the string can also be used with this syntax. Hence:

testform[elem].style.background = "yellow";
      

will do what you want.

+1


source


It looks like you are creating a function to do it anyway. In that case, why not just use the following function:

function changeBackgroundOfElementToYellow(element){
  element.style.background = "yellow";
}

      

And call it with:

changeBackgroundofElementToYellow(testForm.username);

      

In general, I believe the RaYell / kangax method was already better, but this is another option.

+1


source


You need to do eval to do something like this, for example eval ("testform." + Elem + ".style.background = yellow");

-3


source







All Articles