tags:

views:

370

answers:

3

Hi,

I'm trying to determine the width of a string. I'm using the following code but it always return 0. It seems to be that as the span element is created and not already present in the page body, jQuery width() returns 0. Is there a way such that I can get the width of the text without resorting to creating dummy html code in the page?

Thanks :)

$('<span>test</span>').width(); // width = 0
$('span.width').width(); // returns a width value

<body><span class="width">test</span></body>
+1  A: 

You can try adding the control with the css property visibility: hidden to the page before getting the size, therefore avoiding the need to make the element visible.

There is no way to get the width without adding the control, as alot of different things may interfer with the width.

Jan Jongboom
+3  A: 

The element must be present in the DOM in order for the width to be calculated. If you need to calculate this before the user can see the element, try hiding it before putting it into the DOM.

Josh Stodola
@Dominic Thanks for the edit :)
Josh Stodola
A: 

you can sold the problem by using regular expressions

<html>
<body>

<script type="text/javascript">

var str='Hello World';
//look for "Hello"
var patt=/H(ell)o/g;
var result=patt.exec(str);
document.write("Returned value: " +  result[1] + " length=" + result[1].length); 

</script>
</body>
</html>

in your case reg expression should looks like that

/^<[^>]+>(.*?)<\/[^>]+>$/i
Cherven