document.styleSheets is used with an index,
but what If I want to use stylesheet.insertRule with a specific CSS file ?
I know the file's name, which is injected to a page and at some point via JS.
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); }
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')
Why so complicated? You can get a specific document stylesheet by ID or URL without looping through all the stylesheets in the document: var mysheet = $('link#id')[0].sheet;
... or ... var mysheet = $('link[href="/css/style.css"]')[0].sheet;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With