somerandomguy
somerandomguy

Reputation: 41

Is it possible to use a string variable to reference an element in Javascript?

Here's the quick version of the code as it stands right now:

function foo(attributeName, someJSObj, key, newValue)
{
    someJSObj[key].attributeName = newValue;
}

Obviously this doesn't work, since it just creates a new element called attributeName. Is there an easy way to dereference the attributeName into the string that represents some existing attribute on someJSObj?

Upvotes: 0

Views: 85

Answers (3)

Gumbo
Gumbo

Reputation: 655469

You need to use the bracket notation for attributeName as well:

function foo(attributeName, someJSObj, key, newValue)
{
    someJSObj[key][attributeName] = newValue;
}

Now the value of attributeName is used as identifier instead of the identifier attributeName itself.

Upvotes: 5

Buhake Sindi
Buhake Sindi

Reputation: 89179

If I understood you correctly, you could use ECMAScript

function foo(attributeName, someJSObj, key, newValue)
{
    someJSObj[key][attributeName] = newValue;
}

Hope this helps you.

Upvotes: 1

muddybruin
muddybruin

Reputation: 845

Try someJSObj[key].setAttribute(attributeName, newValue)

Upvotes: 0

Related Questions