views:

1751

answers:

1

In jQuery you can get the top position relative to the parent as a number, but you can not get the css top value as a number if it was set in px.
Say I have the following:

 #elem{
  position:relative;
  top:10px;
 }
<div>
 Bla text bla this takes op vertical space....
 <div id='elem'>bla</div>
</div>
$('#elem').position().top; //Returns the number (10+(the vertical space took by the text))
$('#elem').css('top'); //Returns the string '10px'

But I wan't to have the css top property as the number 10...
How would one achieve this?

+6  A: 

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

M4N
Thank you very much!
Pim Jager
You should give the radix too:parseInt($('#elem').css('top'), 10);Forces it to be parsed as base 10, otherwise strings beginning with '0' will be parsed in base 8.
Ben
@Ben: Thats correct. Which I could upvote your answer.
some