How to Gather All Styles from an Element Using Only Its ID
In this question, we aim to develop a function, getStyleById, that retrieves all the style attributes and their corresponding values for a specified element, given only its ID. This function should consider both inline styles and styles defined within CSS files.
Solution:
To achieve this, we can employ a comprehensive approach:
Code Implementation:
<code class="javascript">function getStyleById(id) { return getAllStyles(document.getElementById(id)); } function getAllStyles(elem) { if (!elem) return []; // Empty list if element is absent. 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>
By incorporating these methods, our function can effectively gather all applied styles for a given element, enhancing its utility for various tasks.
The above is the detailed content of How to Retrieve All Styles of an Element Using Only Its ID?. For more information, please follow other related articles on the PHP Chinese website!