Home  >  Article  >  Web Front-end  >  How to Retrieve All Style Attributes of an Element by ID in JavaScript?

How to Retrieve All Style Attributes of an Element by ID in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 22:42:03171browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn