AddRule / insertRule with css selectors

Can I use addRule or insertRule to pass IDs as well? those.:

document.styleSheets[1].addRule('div #3', 'font: 14px verdana');


which will create the rule for the div?

Or is there any known work?


source to share

2 answers

Your code is not working because the selector is not valid. The ID selector is #3

invalid because IDs cannot start with a digit .

To fix this, use an identifier that can be selected with a valid selector, for example #three


document.styleSheets[1].addRule('div #three', 'font: 14px verdana');




Alternatively, you can try this method:

function css_add_file( css_url ) {
    var c = document.createElement('link');
    c.type = 'text/css';
    c.rel = 'stylesheet';
    c.href = css_url; = 'screen';
    c.title = 'dynamicLoadedSheet';


This will allow you to more or less inject CSS rules without having to micromanage their structure.

Example: css_add_inline( "div#three { font-size:14px; font-family: Verdana; }" );



All Articles