Home >Web Front-end >JS Tutorial >How Can I Retrieve a CSS Class's Declaration as a String?

How Can I Retrieve a CSS Class's Declaration as a String?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 11:30:12820browse

How Can I Retrieve a CSS Class's Declaration as a String?

How to Access and Read CSS Rule Values

Question:

How can I obtain the complete CSS declaration of a specific class as a string?

Context:

Consider the following HTML and CSS:

<html>
  <head>
    <style>
      .test {
        width: 80px;
        height: 50px;
        background-color: #808080;
      }
    </style>
  </head>
  <body>
    <div class="test"></div>
  </body>
</html>

Given this CSS, I want to return a string that displays the inline style representation of the .test class, without directly accessing individual style properties.

Answer:

To obtain the complete CSS declaration of a specific class:

function getStyle(className) {
  var cssText = "";

  // Get all CSS rules
  var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;

  // Iterate through rules
  for (var x = 0; x < classes.length; x++) {
    // If the class name matches the rule
    if (classes[x].selectorText == className) {
      // Capture the CSS declaration
      cssText += classes[x].cssText || classes[x].style.cssText;
    }
  }

  // Return the captured CSS declaration
  return cssText;
}

// Usage example:
var result = getStyle(".test");
console.log(result); // Output: "width: 80px; height: 50px; background-color: #808080;"

The above is the detailed content of How Can I Retrieve a CSS Class's Declaration as a String?. 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