Xahed Kamal Xahed Kamal - 7 months ago 9
Javascript Question

Get inline css of an element if there is any (no Internal or External css)

Trying to find a way to retrieve

inline css
of an element if there is any applied. But no internal/external css applied on the element. For example-



$('#get-inline').val( $('#myh1').css('padding-top') );

#myh1{
font-size: 20px;
padding-top: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<h1 id="myh1" style="font-size:30px;">Heading 1</h1>
<input type="text" id="get-inline" />





In above code its retrieving the css applied using the
#myh1
. But i need it to return
null
or
""
. No
0
or
NaN
or anything else.

If i use
$('#myh1').attr('style');
it will return all inline css. But i need a way to get specific css i need to.

Is there way to achieve what i'm trying to? Please help

Looking for a jQuery solution.

Answer

You can get value of any internal css using this script: Try this:

Jsfiddle: https://jsfiddle.net/hfud139c/

html:

<div id="myh1" style="padding-top:10px;height:10px;">Content</div>

Jquery:

$.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;
    };


    var width = $("#myh1").inlineStyle("padding-top");