admin管理员组

文章数量:1405157

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>

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>
Share Improve this question edited Feb 22, 2016 at 11:17 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Feb 22, 2016 at 11:15 hmahdavihmahdavi 2,3824 gold badges46 silver badges98 bronze badges 3
  • document.getElementsByClassName("progress-bar")[0].style.width = "50%"; OR [].forEach.call(document.getElementsByClassName("progress-bar"),function(elem){ elem.style.width="50%" }); – Rayon Commented Feb 22, 2016 at 11:15
  • I use this java script code into onload of body tag. I test this way but don't worked – hmahdavi Commented Feb 22, 2016 at 11:18
  • How many elements are there having class as progress-bar ? – Rayon Commented Feb 22, 2016 at 11:18
Add a ment  | 

2 Answers 2

Reset to default 3

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.

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>

本文标签: htmlChange width of progress bar with javascriptStack Overflow