To create a function that determines the styles applied to an element by its ID, one must consider both inline and CSS file styles. Whereas the current implementation accepts an element's style attribute name alongside its ID, the goal is to acquire all style attributes merely by providing the ID.
Method:
Code:
function getStyleById(id) { return getAllStyles(document.getElementById(id)); } function getAllStyles(elem) { // Check if element exists (empty list if not) if (!elem) return []; var win = document.defaultView || window, style, styleNode = []; // Modern browsers if (win.getComputedStyle) { style = win.getComputedStyle(elem, ''); // Loop through style properties and gather values for (var i = 0; i < style.length; i++) { styleNode.push( style[i] + ':' + style.getPropertyValue(style[i]) ); } } // IE else if (elem.currentStyle) { style = elem.currentStyle; // Loop through currentStyle properties for (var name in style) { styleNode.push( name + ':' + style[name] ); } } // Ancient browsers else { style = elem.style; // Loop through inline styles for (var i = 0; i < style.length; i++) { styleNode.push( style[i] + ':' + style[style[i]] ); } } // Return list of style properties return styleNode; }
The above is the detailed content of How to Extract All Applied Styles for an Element Using Its ID in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!