Is there a way to know the size of a potential DOM node?

.square{ width: 100px; height: 100px; } var h = $('<div/>', {class: 'square'}); alert($(h).width()); // => 0 
  • Can. But in the potential of such objects there can be a lot, so I would like to hear more options. - Alexey Danchin
  • optimize the insertion, there are no other ways, see my example, there are pixels from%, otherwise it will not be counted. (in general, of course, not necessarily position: absolute, everything depends on the task) - zb '22

1 answer 1

paste it into the dom with position absolute; and remove immediately.

 var h = $('<div/>', {class: 'square'}); h.appendTo('body'); h.css('position','absolute'); var w=h.width(); h.detach(); h.css('position',''); $('#out').text(w); //в пикселях console.log(h) 

http://jsfiddle.net/oceog/PSLbC/

if you just need to write to the current css, you can

 var w=h.css(width); //вставлять в этом случае надо только если есть возможность наследования свойства css элементом