I'm trying to dynamically find the width of an item which will have a css class with a specific width, in order to dynamically position its background image (a sprite). However, the item has not yet been added to the DOM. Is there a way to read a class's width property before it's added to the DOM?
javascript/jquery - how to get the width of an element / css class that hasn't been added to dom yet
Asked
Active
Viewed 5,252 times
6
-
Not that I know of reliably. A common approach is to add it off screen (-x,-y) and then check it's width. – CaffGeek Oct 07 '11 at 21:57
-
I don't think JavaScript can access the 'physical' properties of an element until it's been added to the DOM; so I don't think this is possible, no... – David Thomas Oct 07 '11 at 21:58
-
Consensus would say no. I too do not think it is possible. – Joseph Marikle Oct 07 '11 at 22:02
-
possible duplicate of [DOM Element Width before Appended to DOM](http://stackoverflow.com/questions/2921428/dom-element-width-before-appended-to-dom), [Getting the height of an element before added to the DOM](http://stackoverflow.com/questions/5944038/getting-the-height-of-an-element-before-added-to-the-dom) – user113716 Oct 07 '11 at 22:03
2 Answers
1
I believe you cant. Instead add it to a test div,find the width and then remove the div.
$selector.append("<div id='test'></div>");
var widthVal= $selector.find("#test").width();
$("#test").remove();
selector is the element selector you may want to append to. You can associate a class with the "test" div, to have it as "display:none"

Raghav
- 1,014
- 2
- 16
- 34
0
This is a Little Hackie but it should work. Add it to the DOM with the CSS Attribute display: none
so it will be invisible then you can read the with property and delete the element if need be after. Or change its state from Display:none.
Hope this helped.

Eamonn
- 838
- 9
- 10