0

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.

CRAIG
  • 977
  • 2
  • 11
  • 25
  • could you provide any background around the use case, it might help offer a solution – Jay Hewitt Jan 20 '21 at 21:54
  • I am doing some other calculations based on the numbered format I.e. 1, 1.5, 2etc). I suppose I can try to recalculate based on the pixel format but would be easier to just return the numbered format I am already using. – CRAIG Jan 20 '21 at 22:05
  • 1
    Does this answer your question? [Get CSS not-computed property-value with Javascript only](https://stackoverflow.com/questions/46828223/get-css-not-computed-property-value-with-javascript-only) – Heretic Monkey Jan 20 '21 at 23:02
  • @HereticMonkey Possibly, but in a very roundabout way if at all. Was hoping there was an argument I could pass to get it formatted as I wanted, but no worries either way. Thanks! – CRAIG Jan 21 '21 at 00:40

1 Answers1

2

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>
Jay Hewitt
  • 1,116
  • 8
  • 16
  • I think I decided to go ahead and use pixels, but your answer is perfectly fine as well. Thanks! – CRAIG Jan 21 '21 at 00:39