0
const main = document.querySelector('main');

const n = '40px';

const div = document.createElement('div');
div.setAttribute('class', 'grid');

main.appendChild(div);

div.setAttribute('style', 'background-color: #f9f9f9; width: n; height: n'); 

I want n to refer to the value of 40px above. Eventually n will be a user input. (Although I have no idea how I'll get a number to convert to a string+px...but that's an issue for another time).

  • 3
    Use a template string: `setAttribute(\`... width: ${n}; height: ${n}\`);` – Maximilian Burszley May 21 '18 at 17:45
  • 2
    Try using a [template string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals): ``div.setAttribute('style', `background-color: #f9f9f9; width: ${n}; height: ${n}`);`` – mhodges May 21 '18 at 17:45
  • 1
    To answer your "issue for another time", you can do that with [string concatenation](https://stackoverflow.com/questions/16124032/js-strings-vs-concat-method). Example: `var numPx = 40; var myPxStr = numPx + "px";` – mhodges May 21 '18 at 17:47
  • Thanks, everyone! I feel really foolish for not figuring this out, lol –  May 21 '18 at 17:49
  • @00Saad Don't feel too bad. It's still a newer feature. – Maximilian Burszley May 21 '18 at 17:50
  • Just curious, would there be an es5 way of doing the above? –  May 21 '18 at 17:54
  • 1
    @00Saad Same way I concatinated the "px" to numPx. `setAttribute(..., "background-color: #f9f9f9; width: " + n + "; height: " + n + ";");` – mhodges May 21 '18 at 17:55
  • 1
    Ohhh...that would be the syntax, thanks! –  May 21 '18 at 18:01

0 Answers0