Querying an inline style property in jQuery

I am writing a jQuery HTML parser for some specially formatted HTML, and I need to request an inline style for the value.

Inside the code, I go through certain input fields and save this particular style in an array ...

First I use the code that I use to go through these input fields and capture the width. 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 fields

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

Any help appreciated. Thanks!

+4
source share
3 answers

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

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

Live demo

Hence only drunken speculation: theoretically you can get the style attribute and split the values ​​found there based on ; . You can then divide them by : to get key-value pairs.

Sort of:

 $('.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

+8
source

unfortunatelly jquery actually only serves for px values ​​- this is the same with the width () method, btw

A bit dirty, but if the "width" is the only style element of your inputs, you can get the entire style line and analyze it 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 the precision of the float in javascript, you will lose your ... 0000002 at the end. Perhaps you need to parse a number with string methods.

+1
source

Since you are checking attrubute instead of style width

 $(this).css('width') 
-4
source

Source: https://habr.com/ru/post/1346882/


All Articles