hmahdavi
hmahdavi

Reputation: 2354

Change width of progress bar with javascript

I try change width of bootstrap progress bar with java script but don't worked.I wrote this code in head section. Please advice.

document.getElementsByClassName("progress-bar").setAttribute("style", "width:50%");
document.getElementsByClassName("progress-bar").style.width = "width:50%";

Html :

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100">
    </div>
</div>

Upvotes: 2

Views: 7462

Answers (2)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

I would suggest you to use document.querySelector - it returns single element
All major browsers support it

And this is incorrect

document.getElementsByClassName("progress-bar").style.width = "width:50%";
//must be
document.getElementsByClassName("progress-bar").style.width = "50%";

checkout demo below

var percent = 10;
document.querySelector(".progress-bar").style.width = percent + "%";
function increase(){
  percent = percent > 90 ? 10 : percent + 10;
  document.querySelector(".progress-bar").style.width = percent + "%";
}
.progress{
  background: red;
  padding: 3px;
}
.progress-bar{
  background: blue;
  height: 10px;
}
<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100">
    </div>
</div>
<hr />
<button onclick="increase()">increase</button>

Upvotes: 3

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

getElementsByClassName() will return a list of nodes, you should specify the index of the one you want to change :

document.getElementsByClassName("progress-bar")[0].setAttribute("style", "width:50%");
document.getElementsByClassName("progress-bar")[0].style.width = "50%";

Hope this helps.

Upvotes: 3

Related Questions