Home > Web Front-end > CSS Tutorial > How to Extract All Applied Styles for an Element Using Its ID in JavaScript?

How to Extract All Applied Styles for an Element Using Its ID in JavaScript?

Susan Sarandon
Release: 2024-10-29 05:11:03
Original
636 people have browsed it

How to Extract All Applied Styles for an Element Using Its ID in JavaScript?

How to Obtain All Applied Styles for an Element Using Its Id

Problem Description

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.

Answer

Method:

  1. Iterate through CSSStyleDeclaration Object: Obtain property names within the getComputedStyle object; use getPropertyValue to gather values.
  2. Use a Standard For Loop: Employ this method for currentStyle.
  3. Incorporate the Same Looping Technique: Apply this approach for inline styles.

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

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!

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