jQuery is smart enough to calculate dimensions, but only entered once in the DOM.
var html = "<span>My Content</span>"; //hide your element then insert it into the webpage var html_el = $(html).hide(); $('body').append(html_el); //get width and height var width = html_el.width(); var height = html_el.height(); //Remove element from page if no longer needed html_el.remove();
Also note: the <div> block will be displayed at the width of the screen, so the width of the contained elements is incorrectly specified. To get around this, you add these styles to your container: float:left or display:inline-block . Example:
var html = "<div><h2>heading</h2><input type=\"text\" /></div>"; var html_el = $(html).css('float','left').hide();
source share