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.
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.
I had tried many different solutions. This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. So a font set at css file level and one as a style attribute; it returned the correct font.
It is simple! (Sorry, can't find where I originally found it)
Alternatively you can list all the style by cycling through the array
Why not use
.style
of the DOM element? It's an object which contains members such aswidth
andbackgroundColor
.A couple years late, but here is a solution that retrieves both inline styling and external styling:
Pass a jQuery object into
css()
and it will return an object, which you can then plug back into jQuery's$().css()
, ex::)
@marknadal's solution wasn't grabbing hyphenated properties for me (e.g.
max-width
), but changing the firstfor
loop incss2json()
made it work, and I suspect performs fewer iterations:Loops via
length
rather thanin,
retrieves viagetPropertyValue()
rather thantoLowerCase().
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
Basic usage is pretty simple, but he's written a function for that as well:
Hope that helps.