The only option for evaluating the current page's CSS styles is to use document.styleSheets
. It will return a list of CSSStyleSheet
s.
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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…