JavaScript
Article

jQuery css get value without px

By Sam Deering

Sometimes with CSS values they have extensions like px when you get their values using jQuery. This is how you might go about getting the CSS value without the px. If you want to get the css propery values of a dom element such as margin then it will return the px aswell as the value.

For example:

$('#content').css('left');

Would return say: “360px”.

To get just the number value from the css property simple use this:

$('#content').css('left').replace(/[^-d.]/g, '');

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • http://www.lescomplexes.com dods

    parseInt($('#content').attr('left'),10);

  • http://www.echteinfach.tv/ Frank

    great tip, used it :)

    Info/Memo: When using this code on a template that changes, i.e. sometimes the element is not in the html, you need to check against undefined and call replace afterwards, like that:

    if( typeof ($(‘#elementX’).css(“height”)) != “undefined”) {
    $height = $(‘#elementX’).css(“height”);
    // now the replace to get the pixel value
    if($height.replace(/[^-d.]/g, ”) > “16” ) {
    $(‘#elementX’).css(“margin-top”, “-15px”);
    }
    }

    If not some other scripting will break!

  • http://monkeyraptor.johanpaul.net/ Monkey Raptor

    Thanks! This is sweet.

  • http://www.matt-willett.co.uk/ Matt Willett

    It should be: .replace(/[^-d.]/g, ”)

  • pasx

    .replace(/D+$/g, ”) would work better, as the current version returns the string “px”…
    But… .parseInt(“360px”) returns 360 so why bother with regexp at all?

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.