4

Possible Duplicate:
javascript object, access variable property name?

I am messing around with JS, learning a stuff and I am wondering about something... Say you have a function aFunc(), and you accept a string aFunc(val). The value is user defined and is then used to modify the CSS of an element.

For Example:

function aFunc(val){
    document.getElementById('something').style.val = 'red';
}

Say the user entered borderColor, it would somehow refrence borderColor where val is. I do not know how or if this is possible.

EDIT: Please no eval() :)

Community
  • 1
  • 1
MichaelMitchell
  • 1,069
  • 2
  • 13
  • 38

2 Answers2

4

Just use this as a base: JSBIN- Demo on a Div

var type = prompt("style");
var value = prompt("value");
document.body.style[type] = value;
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
  • 2
    Correct answer! In JavaScript object.val is the same as object['val'] so if you want to use a variable for the attribute name, just use [] instead of ".". – masch Dec 21 '12 at 04:18
2

Every object in JavaScript has a method called hasOwnProperty which takes a string value and will return a Boolean value.

var myObj = {
   name: "Josh"
};

myObj.hasOwnProperty("name") === true; //This is true

You can use that to test for the presence of a particular property and then use the method stated in Akhil Sekharan's answer to access that property.

Community
  • 1
  • 1
Josh
  • 44,706
  • 7
  • 102
  • 124