Calculate width of node text in block level element using jQuery

Say I have:

<div>Some variable amount of text.</div> 

How can I get the width (in pixels) of text in a div?

Keep in mind that the amount of text will unpredictably change from div to div.

Thanks!

+4
source share
6 answers

It looks like you want the width of the content, not the div itself, as provided by others. I think you will need to wrap the contents in between in order to then measure the span width. Div will always be as wide as possible. You need something that collapses to the size of the content that you can measure.

+4
source

The best way I've found is to use the CSS rule "display:inline;" to bind only to the textNode given HTML element, and then use the offsetWidth JS method.

 <div style="display:inline;" id="gotWidthInPixels" >Some variable amount of text.</div> <script> //either: var widthInPixels= $('#gotWidthInPixels')[0].offsetWidth; //or var widthInPixels= document.getElementById("gotWidthInPixels").offsetWidth; </script> 

This will give you the exact width in pixels of any HTML element.

+3
source
 var w = $('div').width() 

or use any other selector for div

0
source

Just use width () as follows:

 <div id="mydiv">text text text</div> <script> alert( $('#mydiv').width() ); </script> 
0
source

regarding @mrtsherman if you want to use only text that you could use

 var myDiv = $('#myDiv'); //div width var textWidth = sb.width(); //remove padding and margin from left and right textWidth -= parseInt(sb.css('padding-left') ) + parseInt(sb.css('margin-left') ); textWidth -= parseInt(sb.css('padding-right') ) + parseInt(sb.css('margin-right') ); 
0
source

I had some strange problems where spaces are spaces in which the width calculation in jquery breaks down. I don’t know exactly why, if it is connected with string variables and concatenation, or with the JMVC infrastructure, or just with jQuery.

But by making spaces inextricable spaces

 &nbsp; 

seemed to solve it. just tossing it in case it helps.

0
source

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


All Articles