Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to find all the global styles that apply to a web page?

As a company, we use components (Angular, Vue and React) to build our applications, but we still have a good number of global styles that we inherited from our legacy app.

eg:

.active {
  background: red;
}

Will apply to any element anywhere on the page that has a class of active.

Is there a way, in the browser, to generate a list of all the global (i.e. non-namespaced) style rules that apply to a page, bearing in mind that these might be present inside of third-party libraries, or other miscellaneous legacy JavaScripts?

question from:https://stackoverflow.com/questions/47412570/is-there-a-way-to-find-all-the-global-styles-that-apply-to-a-web-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only option for evaluating the current page's CSS styles is to use document.styleSheets. It will return a list of CSSStyleSheets.

You will want to focus on document.styleSheets[n].cssRules, where n equals which stylesheet you want to evaluate. That will give you a list of all the styles applied by that stylesheet. Each stylesheet will have a cssText and a selectorText property.

If you just want to loop through to find which styles are 'non-namespaced' you should probably just use the selectorText properties.

Here is some more information on MDN about document.styleSheets.

Here is an example (press 'Run code snippet' to see results):

var selectors = [];

var sheets = Array.from(document.styleSheets);

sheets.forEach(function(sheet) {
  // Only Stylesheets from a same-origin domain expose `cssRules` for security reasons
  try {
    var rules = Array.from(sheet.cssRules);
    rules.forEach(function(rule) {
      selectors.push(rule.selectorText);
    });
  } catch (e) {
    // Do something with external stylesheets if you want
  }
});

console.log(selectors);
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Stylesheets</title>
  <style>
    .hello-world {
      background: url(none.gif);
    }
  </style>
  <!-- Won't work as it is not a same-original stylesheet -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <style>
    .foo {
      background: url(none.gif)
    }
    
    .bar {
      background: url(none.gif);
    }
  </style>
</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...