Home > Web Front-end > CSS Tutorial > How to Retrieve All Inline and External Styles of an HTML Element by ID?

How to Retrieve All Inline and External Styles of an HTML Element by ID?

Patricia Arquette
Release: 2024-11-03 07:37:30
Original
432 people have browsed it

How to Retrieve All Inline and External Styles of an HTML Element by ID?

Retrieving Style Properties of an HTML Element by Element ID

You want to craft a function that, when given an element's ID, retrieves all the styles applied to it, both inline and externally defined.

Here's a comprehensive solution:

<code class="js">function getStyleById(id) {
    return getAllStyles(document.getElementById(id));
}

function getAllStyles(elem) {
    if (!elem) return []; // Element does not exist, return 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 browsers..*/
        style = elem.style;
        for (var i = 0; i < style.length; i++) {
            styleNode.push(style[i] + ':' + style[style[i]]);
        }
    }
    return styleNode;
}</code>
Copy after login

Here's a breakdown:

  • Iterate through the style object provided by getComputedStyle to obtain all style properties and their values.
  • For browsers that support currentStyle (IE), iterate over that object.
  • Handle inline styles by iterating directly over the style property of the element.
  • The result is an array of strings in the format "propertyName:propertyValue".

The above is the detailed content of How to Retrieve All Inline and External Styles of an HTML Element by ID?. 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