user1141649 user1141649 - 3 months ago 11
Javascript Question

How to check if property cssRules exists in document.styleSheets[i] object?

How to check if property cssRules exists in document.styleSheets[i] object?

I have found out that I cannot use

if ( sheets[i].hasOwnProperty("cssRules") )
because .cssRules is inherited property.


But when I try to use

if( sheets[i].cssRules !== undefined )


so in debugger (Firefox 48 Toolbox tool) I got exception: SecurityError.

For this reason the code fails.

var cssList = function(node) {
var sheets = document.styleSheets, o = {};
var sheet;
for (var i in sheets) {
if( sheets[i].cssRules !== undefined )
sheet = sheets[i].cssRules;
else
if( sheets[i].rules !== undefined )
sheet = sheets[i].rules;
else
continue;

var rules = sheets[i].rules || sheets[i].cssRules;
}
return o;
}

Answer

You can use 'cssRules' in sheets[i] to detect if sheets[i] has a cssRules property.

However, all stylesheets should have a cssRules property, and then you will always get true.

Your problem is that the cssRules getter throws an error for security reasons.

I think the only way to detect that is with a try statement:

try {
  var rules = sheets[i].cssRules;
} catch(err) {}
if(rules) // ...
Comments