Can jQuery copy an element's bounds (position, size, margins, etc.) to another element?

DNS picture DNS · Oct 6, 2010 · Viewed 8.7k times · Source

I have an element of an arbitrary type. I'd like to create another element, of either the same or a different type that has the same position and size as the first. The element may or may not be positioned.

For example, I might start with a <select> with a certain size, possibly dependent on its contents, i.e. width/height auto. I want to create a new <div> that appears at the same position and has the same size.

I've tried copying the element's float, clear, position, width, height, margins and padding, but this is a little cumbersome. Also, while it works in Firefox, I'm running into some strange issues when testing on Webkit. Before I spend much more time figuring it out, I'd like to know whether there's some jQuery or jQuery UI functionality that already takes care of what I want to do.

I realize that this question is similar to an existing one, but mine has the important distinction of needing to work with elements of differing types, which precludes clone as a solution.

Answer

David Murdoch picture David Murdoch · Oct 6, 2010

This is NOT efficient, tested, or complete. And it is probably similar to what you are already doing. But I thought I'd post it anyways:

var positioningProps = ["float","position","width","height","left","top","marginLeft","marginTop","paddingLeft","paddingTop"];
var select = $("#mySelect");
var div = $("<div>").hide().before(select);
// don't do this kind of loop in production code
// http://www.vervestudios.co/jsbench/
for(var i in positioningProps){
    div.css(positioningProps[i], select.css(positioningProps[i])||"");
}
select.hide();