How to calculate the width of a <div> tag, for example, based on characters in javascript?

I need to create a tag that is absolutely positioned with variable width based on line length, font, size ...

Example:

<div>hello</div> 

To do this, I need about 50 pixels wide. How to do it in javascript? thanks

+4
source share
5 answers

Jesus guys javascript! == jQuery. In any case, to get the width of an element with JavaScript, you can use offsetWidth as follows:

http://jsfiddle.net/gJyKV/1/

(code)

 document.getElementById('test').offsetWidth 

If you get the current width, even if it is absolutely positioned!

+2
source

Create text in the gap, measure its visualized width, and then rearrange it to taste. You can always display it off-screen and then rearrange it if you do not like the jump in position.

http://jsfiddle.net/vW6Wp/

 var test = $('<span>hello</span>').appendTo('body'); alert(test.width()); 
+1
source

I believe jQuery library also offers this. If you gave this div the identifier "get-width", the following method could return the width:

 $('#get-width').width(); 

You can give this by checking it with the following code:

 <div id="test">hellloooo</div> <script type="text/javascript"> $(document).ready(function() { alert($('#test').width()); } </script> 
+1
source

I donโ€™t know why people always answer things using jquery. jquery is the standard for the scripting language, and if the guy only needs this element with the width of the div to load all of this script. there is something called javascript.

sorry for this big conversation but i just don't like

@tooty you can get this with javascript by catching the div by id and then get offsetWidth

 document.getElementById('divId').offsetWidth 

Yours faithfully

+1
source

You do not need to do complex calculations, just use this (Dom is the way to get the width of an element).

As you can see, the method is complicated, since each browser has a different way to do this. that is, the drive that Mootools made, and primarily in other JavaScript libraries. Do yourself a favor and use one of these libraries.
Here is the Mootools path .

0
source

All Articles