How to print a javascript variable inside an html tag?

How to print a javascript variable inside an html tag?

<script>
  (function() {
     var PORCENTAGEM = '25%';
  })();       
</script>

<div class="progress progress-striped active">
  <div class="progress-bar" style="width: IMPRIMIR PORCENTAGEM AQUI"></div>
</div>

Any light?

Author: Márcio Teixeira, 2014-07-24

2 answers

You can select the element by the class name and set the attribute value, Example:

Demo: JSFiddle

(function() {
    var porcentagem = '25%';
    document.getElementsByClassName('progress-bar')[0].setAttribute("style","width:"+porcentagem);
  })();


Edit:
Just to top it off, it could still be done with jQuery leaner:

$(function(){
   var porcentagem = '25%';
   $('.progress-bar').width(porcentagem);
});

Demo2: JSFiddle

 6
Author: abfurlan, 2014-07-25 01:59:12

To change the CSS of elements directly via javascript you can do like this:

document.querySelector('.progress-bar').style.width = PORCENTAGEM;

In this case will select the first element with class "progress-bar" and change its width to the value that the percentage variable has at the moment.

I'm not sure how it will update the percentage value.

Example: http://jsfiddle.net/9LT7J /

By the way could do whatever you want with html5 <progress>, in which case it would like this:

<div class="progress progress-striped active">
    <progress max="100" class="progress-bar" value="0"></progress>
</div>

Example: http://jsfiddle.net/9LT7J/1 /

 5
Author: Sergio, 2014-07-24 21:19:28