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?

+3


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');

      

+8


source


Alternatively, you can try this method: http://pp19dd.com/2012/01/add-inline-css-or-remote-css-file-with-javascript/

function css_add_file( css_url ) {
    var c = document.createElement('link');
    c.type = 'text/css';
    c.rel = 'stylesheet';
    c.href = css_url;
    c.media = 'screen';
    c.title = 'dynamicLoadedSheet';
    document.getElementsByTagName("head")[0].appendChild(c);
}

      



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; }" );

+2


source







All Articles