Gray_Hound
Gray_Hound

Reputation: 127

addRule / insertRule with css selectors

Is it possible to use addRule or insertRule to also pass id selectors ? ie :

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

which would create a rule for div ?

Or is there any kind of known work around ?

Upvotes: 3

Views: 7417

Answers (2)

pp19dd
pp19dd

Reputation: 3633

Alternatively, you could 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);
}

It'll permit you to more or less inject CSS rules without having to micromanage their structure.

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

Upvotes: 2

BoltClock
BoltClock

Reputation: 724262

Your code doesn't work because the selector is invalid. The ID selector #3 is invalid because ID selectors cannot begin with a digit.

To fix this, use an ID which can be selected with a valid selector, for example #three:

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

Upvotes: 8

Related Questions