Sunday, July 28, 2013

jQuery check if element has a specific style property defined inline

Here's a very simple (probably in much need of improvement) plugin I've thrown together that will get you the value of an inline style property (and return undefined if that property is not found):

​(function ($) {
    $.fn.inlineStyle = function (prop) {
         var styles = this.attr("style"),
             value;
         styles && styles.split(";").forEach(function (e) {
             var style = e.split(":");
             if ($.trim(style[0]) === prop) {
                 value = style[1];          
             }                   
         });  
         return value;
    };
}(jQuery));

You can call it like this:

//Returns value of "width" property or `undefined`
var width = $("#someElem").inlineStyle("width");



Or you can use more simple way to do this as:

if ( $("#someElem")[0].style["width"] ) {
    //Has the style property inline
}
else {
    //Has not the style property inline
}

No comments:

Post a Comment