Reputation: 459
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>
Upvotes: 0
Views: 607
Reputation: 68413
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>
Upvotes: 3