Can I style an element with JavaScript variable?

Viewed 156

Am trying to work out a fee progress bar. I have calculated the percentage of the width of the progress with JavaScript and it's a variable z. So I am trying to style the element with the variable z and it's not working when I add % to it. Here is my code:

<html>
<body>
  <div class="mybar">
    <div class="myprogress" id="progress">
    </div>
  </div>
  <script>
    window.onload=function(){
      var fee=document.getElementById("fee").innerHTML;
      var bill=document.getElementById("bill").innerHTML;
      var y=(fee/bill);
      var z=(y*100);
      document.getElementById("progress").style.width="z%";
    }
  </script>
</body>
</html>
3 Answers

Since z is a variable, and you want to create a string with the % sign afterwards, you need to append them:

 document.getElementById("progress").style.width = z + '%';

A Summary of available ways to style using JavaScript.

Plain Javascript

Either concatenate z and the Percent sign:

document.getElementById("progress").style.width = z + "%";

Or use string template literals:

document.getElementById("progress").style.width=`${z}%`;

JQuery

$("#progress").css("width", z + "%");

or

$("#progress").css("width", `${z}%`);
Related