How to print a javascript variable inside an html tag?

Asked

Viewed 16,197 times

5

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>

Some light?

2 answers

6


You can select the element by 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 complement, it could still be done with jQuery more streamlined:

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

Demo2: Jsfiddle

5

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

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

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

I’m not sure how you’re gonna update the percentage.

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

By the way could do with the <progress> 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: http://jsfiddle.net/9LT7J/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.