2

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>
3
  • document.getElementsByClassName("progress-bar")[0].style.width = "50%"; OR [].forEach.call(document.getElementsByClassName("progress-bar"),function(elem){ elem.style.width="50%" }); 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 Commented Feb 22, 2016 at 11:18
  • How many elements are there having class as progress-bar ? Commented Feb 22, 2016 at 11:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked correctly . Is this code works in Internet Explorer?
3

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.