Firefox Not Able to Enumerate Document.Stylesheets[].Cssrules[]

Firefox not able to enumerate document.styleSheets[].cssRules[]

You can get that error when trying to read a stylesheet loaded from a different domain or server, or trying to read an @import rule.

For your purpose, just check the document.styleSheets.length .

Is it possible to select stylesheet.cssRule[] with a class name or ID?

Unfortunately, there is no such method available. Specifically, the API only allows for deleting and inserting rules. On top of that, browsers may deny access to even that based on where the stylesheet originates.

Read more about it here:

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet

get document.styleSheets by name instead of index?

Use this, and keep in mind:

For security reasons, Opera and
Mozilla will not allow you to access
the cssRules collection of a
stylesheet from another domain or
protocol. Attempting to access it will
throw a security violation error

function setStyleRule (selector, rule, sheetName) {
var sheets = document.styleSheets,
stylesheet = sheets[(sheets.length - 1)];

for( var i in document.styleSheets ){
if( sheets[i].href && sheets[i].href.indexOf(sheetName + ".css") > -1 ) {
stylesheet = sheets[i];
break;
}
}

if( stylesheet.addRule )
stylesheet.addRule(selector, rule);

else if( stylesheet.insertRule )
stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
}


Update - shorter code:

function getSetStyleRule(sheetName, selector, rule) {
var stylesheet = document.querySelector('link[href*=' + sheetName + ']')

if( stylesheet ){
stylesheet = stylesheet.sheet
stylesheet.insertRule(selector + '{ ' + rule + '}', stylesheet.cssRules.length)
}

return stylesheet
}

// Usage example
getSetStyleRule('main', 'body', 'background:red')

What is the best way to have Firefox-specific CSS rules now after @-moz-document has been limited

You could use a @supports feature query testing some specific vendor prefixed -moz- value, e.g.

Codepen demo


<p class="moz">Is it Mozilla?</p>

CSS

.moz::after { content: " nope."}

@supports (display: -moz-grid) {
.moz::after { content: " yep!"}
}

Note that this method will work until that specific value (e.g. -moz-grid) is not removed from the vendor in the future and can be also used to detect other vendor values (like display: -webkit-box or display: -ms-flexbox)



Related Topics



Leave a reply



Submit