Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  157] [ 4]  / answers: 1 / hits: 174652  / 15 Years ago, thu, april 16, 2009, 12:00:00

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?



I know it would work if they were a style attribute with attr(), but all of my styles are in an external style sheet.


More From » jquery

 Answers
122

A couple years late, but here is a solution that retrieves both inline styling and external styling:



function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}

function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == string) {
css = css.split(; );
for (var i in css) {
var l = css[i].split(: );
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}


Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css(), ex:



var style = css($(#elementToGetAllCSS));
$(#elementToPutStyleInto).css(style);


:)


[#99698] Wednesday, April 8, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;