How to calculate padding

by oatkiller

HTML

<div style="padding-top: 1.234234em">snarf</div>

JavaScript

$.fn.padding = function () {
    // clone the interesting element
    // append it to body so that CSS can take effect
    var clonedElement = this.
        clone().
        appendTo(document.body);
    
    // get its height
    var innerHeight = clonedElement.
        innerHeight();
    
    // set its padding top to 0
    clonedElement.css("padding-top","0");
    
    // get its new height
    var innerHeightWithoutTopPadding = clonedElement.
        innerHeight();
    
    // remove the clone from the body
    clonedElement.remove();
    
    // return the difference between the height with its padding and without its padding
    return innerHeight - innerHeightWithoutTopPadding;
                     
};

// Test it

console.log($("div").padding()); // prints 19 in Chrome 23
console.log($("div").css("padding-top")); // prints 19.733333587646484px