How to print a javascript variable inside an html tag?

4

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?

    
asked by anonymous 24.07.2014 / 22:04

2 answers

5

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

Demo: JSFiddle

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


Edit:
Just to complement, it could still be done with jQuery in a leaner way:

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

Demo2: JSFiddle

    
24.07.2014 / 22:10
5

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

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

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

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

Example: link

By now could do whatever it wants with <progress> of HTML5, in which case it would do so:

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

Example: link

    
24.07.2014 / 22:09