I am looking for a way to use jQuery to return a computed styles object for a 1st matched element. Then I could pass this object to another jQuery css method call.
For example, with width, I can do the following to make 2 divs of the same width:
$('#div2').width($('#div1').width());
It would be nice if I could make the text input look like an existing range :
$('#input1').css($('#span1').css());
where .css () without an argument returns an object that can be passed . css (obj) .
(I cannot find the jQuery plugin for this, but it seems to exist. If it does not exist, I will turn mine below into a plugin and put it with all the properties that I use.)
Basically, I want to pseudo-clone certain elements , but use a different tag . For example, I have an li element that I want to hide and put an input element on it that looks the same. When the user types, it looks like they are editing the inline element .
I am also open to other approaches to this pseudo-cloning issue for editing. Any suggestions?
Here is what I have now. The only problem is just getting all the possible styles. It can be a ridiculously long list.
jQuery.fn.css2 = jQuery.fn.css; jQuery.fn.css = function() { if (arguments.length) return jQuery.fn.css2.apply(this, arguments); var attr = ['font-family','font-size','font-weight','font-style','color', 'text-transform','text-decoration','letter-spacing','word-spacing', 'line-height','text-align','vertical-align','direction','background-color', 'background-image','background-repeat','background-position', 'background-attachment','opacity','width','height','top','right','bottom', 'left','margin-top','margin-right','margin-bottom','margin-left', 'padding-top','padding-right','padding-bottom','padding-left', 'border-top-width','border-right-width','border-bottom-width', 'border-left-width','border-top-color','border-right-color', 'border-bottom-color','border-left-color','border-top-style', 'border-right-style','border-bottom-style','border-left-style','position', 'display','visibility','z-index','overflow-x','overflow-y','white-space', 'clip','float','clear','cursor','list-style-image','list-style-position', 'list-style-type','marker-offset']; var len = attr.length, obj = {}; for (var i = 0; i < len; i++) obj[attr[i]] = jQuery.fn.css2.call(this, attr[i]); return obj; }
Edit: I have been using the code above for some time now. It works well and behaves exactly the same as the original css method with one exception: if 0 arguments are passed, it returns an object with a computed style.
As you can see, it immediately calls the original css method, if applicable. Otherwise, it gets the computed styles of all the listed properties (compiled from the list of classified Firebug styles). Although he receives a long list of values, he is pretty quick. Hope this is helpful to others.