CRAIG
CRAIG

Reputation: 1029

With jQuery retrieve the line-height in numbered format instead of pixels

My element is set to this line-height:

<div id="line-height" style="line-height:1.5">HOWDY</div>

However, when I try to get the line-height with jQuery, it gives me the pixel version instead of the number version.

var lineheight = jQuery('#line-height').css('line-height');

console.log(lineheight);

And in the console, it returns to me a number with px after it instead of 1.t pt

How can I get the data in the correct format.

Upvotes: 0

Views: 34

Answers (1)

Jay Hewitt
Jay Hewitt

Reputation: 1126

Not sure you can get a value other than pixels in this way, however, you could use data attributes to populate both the styling, and give you a way to access what you want.

Note. I've used the data attribute to hold the style mainly to use less code, however this means there will be a flicker in appearance too, so would be more ideal to have the style already set, or better in the CSS.

jQuery(function() {
    // Set line heights based on data attribute if necessary
    jQuery("[data-lh]").each(function(){
      var _self = jQuery(this);
      _self.css("line-height", _self.data("lh"));
    });
    
    // Get Line Height from data Attribute
    var lineheight = jQuery('#line-height').data('lh');
    console.log(lineheight);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<div id="line-height" data-lh="1.5">HOWDY</div>

Upvotes: 2

Related Questions