4

I am writing a JQuery HTML parser for some particularly formatted HTML and I need to query an inline style for a value.

Within the code I am stepping through particular input fields and saving out this particular style to an array...

First here is the code I am using to step through these input fields and grab the widths. This works but does not return the correct width value (I want the EM value).

$('.inputBox',this).each(function(index)
{
   widthArray[widthArray.length] = $(this).attr('width');
}

Here is a simplified example of one of the input boxes

<input style="width:1.9500000000000002em;" maxlength="3" tabindex="1" class="inputBox" type="text">

Any help appreciated. Thanks!

kapa
  • 77,694
  • 21
  • 158
  • 175
Julian Young
  • 872
  • 2
  • 9
  • 21

3 Answers3

8

Of course the easiest way is to get it from the style attribute of this.

$('.inputBox', this).each(function(index) {
   widthArray[widthArray.length] = this.style.width;
});

Live Demo

From here on this is just drunken speculation: theoretically, you can get the style attribute and split the values found in there based on ;. Then you can further split them on : to get the key-value pairs.

Something like:

$('.inputBox', this).each(function(index) {
   var stylestemp = $(this).attr('style').split(';');
   var styles = {};
   var c = '';
   for (var x = 0, l = stylestemp.length; x < l; x++) {
     c = stylestemp[x].split(':');
     styles[$.trim(c[0])] = $.trim(c[1]);
   }
   widthArray[widthArray.length] = styles.width;
});

Live Demo of Drunken Speculation

kapa
  • 77,694
  • 21
  • 158
  • 175
1

unfortunatelly jquery actually serves only px-values - it's the same with the width() method, b.t.w.

A little dirty, but if "width" is the only style-element of your inputs, you could retrieve the whole style string and parse it by yourself:

var inputStyle = $("input").attr('style');
// make an array [ 'width', '1.9500000000000002em;' ]
var styleParts = inputStyle.split(':');
// make float from 1.9500000000000002em; --> 1.95
var widthEm = parseFloat(styleParts[1]);

Due to float precision in javascript you'll lose your ...0000002 at the end. Maybe you'll need to parse the number with string methods.

HBublitz
  • 670
  • 4
  • 6
-4

Because you checking the attrubute instead of the style width

$(this).css('width')
liron
  • 375
  • 2
  • 12
  • Thanks but I tried that already, it returns a pixel width. I want the actual EM value declared in the style. – Julian Young Apr 06 '11 at 09:28
  • -1 this won't work. See http://stackoverflow.com/questions/5475589/jquery-css-function-not-returning-expected-values/5476075#5476075 – kapa Apr 06 '11 at 10:19