Categories
JavaScript Answers

How to Get the CSS Top Property Value as a Number Rather Than a String with JavaScript?

Spread the love

To get the CSS top property’s value as a number rather than a string, we should remove px from the end of the string.

Then we can convert that to a number with the + operator.

For instance, if we have the following div:

<div style='position: absolute; top: 10px'>  
  hello  
</div>

Then we can get the top CSS property’s value by writing:

const topCss = +$('div').css('top').replace('px', '')  
console.log(topCss)

We call css with 'top' to get the top property value as a pixel.

Then we call replace to remove 'px' by calling it with 'px' and an empty string.

Then we use the unary + operator to convert the number string into a number.

So topCss is 10.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *