Yaroslavps
Yaroslavps

Reputation: 3

Why does element.style.property not work with template strings?

Maybe I am doing something wrong, but for some reason if I try to set the style property of an element in Javascript using template strings, it just doesn't work, whereas using old style concatenation works. For example, this works:

    containerAnim1.style.backgroundColor = 'rgb('
      + currentColor[0] + ', '
      + currentColor[1] + ', '
      + currentColor[2] + ')';

But this for some reason doesn't:

    containerAnim1.style.backgroundColor = 
      `rbg(${currentColor[0]}, ${currentColor[1]}, ${currentColor[2]})`;

I was going mad trying to figure out what was wrong with my code, until I figured out that both Chromium and Firefox didn't like template strings for setting style properties of DOM objects.

Why does this not work?

Upvotes: 0

Views: 59

Answers (1)

Solo
Solo

Reputation: 6967

You misspelled rgb, you have rbg.

const content = document.getElementById('content');

const currentColor1 = [255, 0, 0];
const currentColor2 = [0, 0, 0];


setTimeout(() => {
  let s = 'rgb(' +
    currentColor1[0] + ', ' +
    currentColor1[1] + ', ' +
    currentColor1[2] + ')';
  console.log('regular:', s);
  content.style.backgroundColor = s;
}, 1000);

setTimeout(() => {
  let s = `rgb(${currentColor2[0]}, ${currentColor2[1]}, ${currentColor2[2]})`;
  console.log('literal:', s);
  content.style.backgroundColor = s;
}, 2000);
<div id="content" style="height: 200px; width: 200px; background: #eee;"></div>

Upvotes: 1

Related Questions