0

I want to change the width by adding 20%. My div class width in percentage. For example i have div with width 20%. I am using class name for stylesheet. When each time the page loading it want increase by 10%. The code is shown below. the avascript code document.getElementsByClassName("box")[0].style.width; is not working` proper. Please help me.

html

<div class="box">

var width = document.getElementsByClassName("box")[0].style.width;

var n = width + 20%;

width = n;
.box{
  width:40%;
  height:300px;
  background-color:red;
}
<div class="box">
</div>

Fazil fazi
  • 439
  • 1
  • 4
  • 15
  • 1
    `var n = width + 20%;` this is not valid javascript. You would have noticed if you ran your own code and checked the debugger. – Federico klez Culloca Dec 07 '17 at 09:40
  • [Get element CSS property (width/height) value as it was set (in percent/em/px/etc)](https://stackoverflow.com/questions/9730612/get-element-css-property-width-height-value-as-it-was-set-in-percent-em-px-et) – Alive to die - Anant Dec 07 '17 at 10:06

1 Answers1

3

This line has a syntax error

width + 20%;

If you want to calculate percentage then

width = width + width*20/100;

Edit

As @Rory pointed out in the comments, your width value isn't getting set because width value isn't getting fetched correctly at first place, here is the updated code

var ele = document.getElementsByClassName("box")[0];
var width = parseInt(window.getComputedStyle(ele).width); //get computed style instead of style property
width = width + width*20/100;
document.getElementsByClassName("box")[0].style.width = width;

Edit 2

As pointed out by @Anant, if you want to increase with in percentage, then

var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ;
var ele = document.getElementsByClassName("box")[0];
var width = parseInt(fn(ele)); //get computed style instead of style property
console.log(width);
//width = width + width*20/100;
width = (width + 20) + "%";
console.log(width);
document.getElementsByClassName("box")[0].style.width = width;

Demo

var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ;

var ele = document.getElementsByClassName("box")[0];
var width = parseInt(fn(ele)); //get computed style instead of style property
console.log(width);
//width = width + width*20/100;
width = (width + 20) + "%";
console.log(width);
document.getElementsByClassName("box")[0].style.width = width;
.box{
  width:40%;
  height:300px;
  background-color:red;
}
<div class="box">
</div>
gurvinder372
  • 66,980
  • 10
  • 72
  • 94