Home >Web Front-end >CSS Tutorial >How to Retrieve All Style Attributes of an Element by ID in JavaScript?
Getting All Style Attributes by Element ID
You can fetch all style attributes applied to an element by providing its ID using the following method:
Looping Through CSSStyleDeclaration Object:
Iterate through the indexes of the CSSStyleDeclaration object (getComputedStyle) to obtain each known property name. Use getPropertyValue with this name to retrieve the value.
Processing Inline Styles:
For inline styles, use the same looping method as for other style types.
Putting It All Together:
Here's the code:
<code class="javascript">function getStyleById(id) { return getAllStyles(document.getElementById(id)); } function getAllStyles(elem) { if (!elem) return []; 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]) ); } } 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; }</code>
The above is the detailed content of How to Retrieve All Style Attributes of an Element by ID in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!