Home > Article > Web Front-end > How can I get all the style attributes and their values applied to an HTML element by its ID using JavaScript?
Intro
Need to retrieve all the style attributes and their values applied to an HTML element using only its ID? This question delves into how to go about doing exactly that.
Understanding the Problem
The objective is to create a function, getStyleById, that takes the ID of an element and returns a list of all the style attributes and their corresponding values. This function should account for both inline and style attributes defined in external CSS files.
Crafting the Solution
To achieve this, consider the following methods:
Code Implementation
<code class="javascript">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; }</code>
Usage
To use this function, simply call getStyleById with the ID of the element. For instance:
<code class="javascript">console.log(getStyleById('my-element'));</code>
This will print an array containing all the style attributes and their values applied to the element with the ID 'my-element'.
The above is the detailed content of How can I get all the style attributes and their values applied to an HTML element by its ID using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!