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

Susan Sarandon
Release: 2024-10-30 22:42:03
Original
181 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!