Moran
Moran

Reputation: 435

Better way to get the border width in javascript?

I use this :

var playGard =document.getElementsByClassName("playGard")[0];

var borderW= getComputedStyle(playGard,null).getPropertyValue('border-left-width').substr(0,2);

I get the value "10".

There is a better shorter way in javascript?

(Get the value as a number)

Upvotes: 0

Views: 1615

Answers (1)

user663031
user663031

Reputation:

Obviously, substr(0, 2) is not a good idea, because it won't work if the width is less than 10, or greater than 100.

Instead, just remove the "px" string (if it's there; it might not be if the value is 0):

+val.replace('px', '')

The leading + is to convert this to a number.

But why?

The more interesting question is why you're trying to get the border width. What were you planning to do with it? Using getComputedStyle is a bit of an anti-pattern. It often indicates that you're trying to maintain application state within CSS, which is never a good idea.

Upvotes: 2

Related Questions