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
-
Not that I know of reliably. A common approach is to add it off screen (-x,-y) and then check it's width.CaffGeek– CaffGeek2011-10-07 21:57:53 +00:00Commented Oct 7, 2011 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– David Thomas2011-10-07 21:58:36 +00:00Commented Oct 7, 2011 at 21:58
-
Consensus would say no. I too do not think it is possible.Joseph Marikle– Joseph Marikle2011-10-07 22:02:43 +00:00Commented Oct 7, 2011 at 22:02
-
possible duplicate of DOM Element Width before Appended to DOM, Getting the height of an element before added to the DOMuser113716– user1137162011-10-07 22:03:47 +00:00Commented Oct 7, 2011 at 22:03
Add a comment
|
2 Answers
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"