Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get document.styleSheets by name instead of index?

Tags:

javascript

css

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.

like image 223
vsync Avatar asked Nov 05 '09 10:11

vsync


2 Answers

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') 
like image 194
vsync Avatar answered Oct 04 '22 11:10

vsync


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;

like image 32
suncat100 Avatar answered Oct 04 '22 13:10

suncat100