How to get all the applied styles of an element by just giving its id?
Solution 1:
Use the following method:
- Loop through the indexes of the
CSSStyleDeclaration
object (getComputedStyle) to get each known property name. UsegetPropertyValue
+ this name to get the value.
Code optimalization: Do not usegetComputedStyle
for each iteration, but store it in a variable outside the loop. - Use an ordinary
for ( name in object )
loop forcurrentStyle
. - Use the same looping method for inline styles
Code:
function getStyleById(id) {
return getAllStyles(document.getElementById(id));
}
function getAllStyles(elem) {
if (!elem) return []; // Element does not exist, empty list.
var win = document.defaultView || window, style, styleNode = [];
if (win.getComputedStyle) { /* Modern browsers */
style = win.getComputedStyle(elem, '');
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style.getPropertyValue(style[i]) );
// ^name ^ ^ value ^
}
} else if (elem.currentStyle) { /* IE */
style = elem.currentStyle;
for (var name in style) {
styleNode.push( name + ':' + style[name] );
}
} else { /* Ancient browser..*/
style = elem.style;
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style[style[i]] );
}
}
return styleNode;
}