0

I would need to divide a value given by .style.width function in Javascript. My code looks like this:

    var x = document.getElementsByClassName("item");
    var i;

    var v = x[0].style.width; 

In variable 'v' I have some value in pixels, e.g. 200px width. I would need to divide this value by 2 to get 100px. But this formula doesn't work: var v = x[0].style.width / 2;

What am I doing wrong? Thanks for help.

2
  • var v = parseInt(x[0].style.width) / 2; Commented May 9, 2020 at 8:42
  • Maybe var v = x[0].clientWidth / 2 + "px"; Commented May 9, 2020 at 8:44

1 Answer 1

1

width will be string. Convert it to number before dividing. This example uses getComputedStyle to get actual width of a dom element

let elem = document.getElementById('test');
let compStyles = window.getComputedStyle(elem);
const widthInteger = parseInt(compStyles.width, 10);
const halfWidth = widthInteger / 2;
console.log(halfWidth)
.test {
  height: 200px;
  width: 200px;
  border: 1px solid green;
}
<div class='test' id='test'></div>

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

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.