Googlebot
Googlebot

Reputation: 15683

How to use a variable in JavaScript command?

Consider a simple JS function as

function test(property, color) {
    var element = document.getElementById("test");
    element.style.PROPERTY = color; // I want to use a variable for this command
}

In a typical JS command of element.style.PROPERTY, I want to introduce the property as a variable. This is a very basic example; what is the best approach to use variables in JS command lines?

Upvotes: 0

Views: 1199

Answers (2)

craigforster
craigforster

Reputation: 2669

element.style[property] = color; should work.

Upvotes: 1

zerkms
zerkms

Reputation: 255005

Use it as:

element.style[property]

This is a very basic example; what is the best approach to use variables in JS command lines?

It depends on what you want to achieve. In this case - just use [...]

Upvotes: 3

Related Questions