Calculate width of text node in a block level element using jQuery

懵懂的女人 提交于 2019-12-05 16:47:25

Sounds like you want the width of the contents, not of the div itself as others have provided. I think that you will need to wrap your contents in a span so that you can then measure the width of the span. The div will always be as wide as possible. You need something that collapses to the size of the content that you can measure instead.

Samstr

The best way I found is to use CSS rule "display:inline;" to bound only textNode of given HTML Element, then use 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 exact width in pixels of any HTML Element.

var w = $('div').width()

or use any other selector for the div

Just use width() like so:

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

with regards to @mrtsherman if you want the width of just the text 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') );

i had some weird issues where whitespace spaces where breaking the width calculation in jquery. not sure exactly why, if it was because of string variables and concatenation, or the JMVC framework, or just jQuery.

But, making the spaces non-breaking spaces

&nbsp;

seemed to solve it. just throwing that out there in case it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!