Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use a variable (number value) into another value (like pixel value) in javascript?

I’m trying to use a variable as a pixel value but I don’t know how to convert. Like this:

a = 20;
const h1 = document.querySelector("h1");
h1.style.fontSize = '{a}px';

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading