Reputation: 19386
Here's how you get one css attribute using jQuery:
$('someObject').css('attribute')
How do you get them all? (without specifying and preferably in the following format so it can be reapplied with jQuery later):
cssObj = {
'overflow':'hidden',
'height':'100%',
'position':'absolute',
}
Thanks!!
EDIT
The methods I'm trying to get are declared in a style sheet (they are not inline). Sorry for not specifying.
Upvotes: 26
Views: 44251
Reputation: 166
For a platform (the name is subject to nondisclosure) where the Chrome or Safari DevTools/WebInspector are not available, and you need to dump the styles to the log.
dumpCssFromId (id) {
const el = document.getElementById(id);
const styles = window.getComputedStyle(el);
return Object.keys(styles).forEach((index) => {
const value = styles.getPropertyValue(index);
if (value !== null && value.length > 0) {
console.log(`style dump for ${id} - ${index}: ${value}`);
}
}, {});
}
Upvotes: 0
Reputation: 379
window.getComputedStyle(element);
// For example
var element = document.getElementById('header');
window.getComputedStyle(element);
Upvotes: 1
Reputation: 8070
Not sure how cross-browser this one is, but it works in Chrome -
https://gist.github.com/carymrobbins/223de0b98504ac9bd654
var getCss = function(el) {
var style = window.getComputedStyle(el);
return Object.keys(style).reduce(function(acc, k) {
var name = style[k],
value = style.getPropertyValue(name);
if (value !== null) {
acc[name] = value;
}
return acc;
}, {});
};
Upvotes: 6
Reputation: 4553
See this live example using the jQuery attribute selector
$(document).ready(function() {
alert($("#stylediv").attr('style'));
});
Upvotes: 17
Reputation: 4288
What about something like this:
jQuery CSS plugin that returns computed style of element to pseudo clone that element?
It is ugly, but it appeared to work for the poster...
This also may be of interest: https://developer.mozilla.org/en/DOM:window.getComputedStyle
Upvotes: 9