0

My Javascript goes something like this:

if (choice=="green") {
    var choicecolor="#00"+num+"00"
}
...

And I need to access the variable 'choicecolor' inside an html tag. This was my failed attempt:

<div id="box" style="background-color: "choicecolor>...</div>

How can I properly put the variable inside the tag?

  • It seems your brain tends to see two way bindings as a natural function, start using frameworks like angular, knockout, ember etc and you can use the same variable names (kinda) inside the html templates and they will always be in sync – makeitmorehuman May 29 '15 at 00:12
  • 1
    not sure why you are changing the backgroundColor but maybe changing the element class might be a better idea http://stackoverflow.com/q/195951/1959948 – Dalorzo May 29 '15 at 00:15
  • `Element.style.backgroundColor = '#0f0';` You don't put JavaScript variables into HTML, you just affect the DOM with it, unless you're using `document.write()` which is not recommended. `Element.style.cssText = 'background-color:#0f0;` will overwrite the entire HTML `style` attribute, which I also don't recommend. Probably really want to use `Element.className = 'choicecolor';` and just have your CSS set up already. `Element` could be `document.getElementById('box')` in this case. – StackSlave May 29 '15 at 00:20

1 Answers1

2

Use the DOM API to set it. Make sure the element exists first.

document.getElementById('box').style.backgroundColor = choicecolor;

Or you could use a templating engine, but that is more problematic.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445