You want to craft a function that, when given an element's ID, retrieves all the styles applied to it, both inline and externally defined.
Here's a comprehensive solution:
<code class="js">function getStyleById(id) { return getAllStyles(document.getElementById(id)); } function getAllStyles(elem) { if (!elem) return []; // Element does not exist, return 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 browsers..*/ style = elem.style; for (var i = 0; i < style.length; i++) { styleNode.push(style[i] + ':' + style[style[i]]); } } return styleNode; }</code>
Here's a breakdown:
The above is the detailed content of How to Retrieve All Inline and External Styles of an HTML Element by ID?. For more information, please follow other related articles on the PHP Chinese website!