UPDATE [08/04/11] – Slightly updated version of this method, along with a helper method to copy the styles to a jQuery instance, can be found here.

While this method is something of a resource-hog, and the net result can usually be structured a little more cleanly, occasionally you might want to clone the style of some arbitrary object and pass that to other elements. jQuery’s standard .css() method won’t do this – nor should it – as it’ll only return the styles set specifically for that element, not those applied by inheritance, or by default due to a tag (e.g., div elements have display:block by default). For example, say you have a set of links in nested lists that you want to drag, and drop onto another element that was not a list, but retain it’s existing formatting. If you have a css selector like:

Once the link element became a child of the new parent – say, a div – it’d lose it’s color style definition.

This snippet will return an Object with all style properties currently displayed by the calling element, regardless of how those style properties were assigned. This object can then be passed to other elements by passing the returned object to the jQuery .css method.

Note that this will retrieve all style properties – even those that weren’t explicitly defined – which can be a very long list.

Usage might look like this: