-3

The simple code for change width of a class in css code using javascript is not working. I have given the width is 200px. Then i want to change the width to 50px. i want to use a javascript code to change width. But it is not working.

document.getElementsByClassName("main").style.width = "50px";
.main {
  width: 200px;
  height: 200px;
  background-color: red;
}
<div class="main"></div>

fiddle: https://jsfiddle.net/33zc0efq/

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
Fazil fazi
  • 439
  • 1
  • 4
  • 15

1 Answers1

2

document.getElementsByClassName returns an array of object so you need to specify index for that. Change it to document.getElementsByClassName("main")[0].style.width="50px";

document.getElementsByClassName("main")[0].style.width="50px";
.main{
  width:200px;
  height:200px;
  background-color:red;
}
<div class="main">
</div>
Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31