I am trying to use a JavaScript variable as an HTML pixel value, but I don't know how to use it in a string.
Here's the code:
a = 20;
const h1 = document.querySelector("h1");
h1.style.fontSize = '{a}px';
I am trying to use a JavaScript variable as an HTML pixel value, but I don't know how to use it in a string.
Here's the code:
a = 20;
const h1 = document.querySelector("h1");
h1.style.fontSize = '{a}px';
You can use Template literals, which add in a string to the second string.
Here's an example:
const a = 50;
const h1 = document.querySelector("h1");
h1.style.fontSize = `${a}px`;
<h1> Hello </h1>
Or, you can use concatenation for bringing strings together:
a + "px";
// "50px"
Be careful when using concatenation, because if you use a number (like 50) it will add up the string plus the number. You can use a.toString()
or String(a)
to convert it to a string.
50 + "px"; // "50px"
"50" + "px"; // "50px"
(50).toString() + "px"; // "50px"
String(50) + "px"; // "50px"