views:

73

answers:

2

I'm creating a style element like this :

function createMyStyle(selector , rule){
   j$("head").append('<style type="text/css">' + selector + '{' + rule + '}' + '</style>');
}

Now, I don't want to create this element every time, but to find out if this element was inserted already, and then use something like this to add my rules to it:

if( stylesheet.addRule ){
 stylesheet.addRule(selector, rule);
} 
else if( stylesheet.insertRule ){
 stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
}

PS: I create this in one piece and not with pure DOM because IE can't do innerHTML to document.createElement('style') ...

I tried giving the and ID and do something like

for( var i in document.styleSheets ){
  if( !document.styleSheets[i].id){

but this can't be done cause theres no ID attribute to it.

A: 

Try doing something like this with jQuery:

if($("style").length > 0){
  // this means you have a style  element in your document
}
Guillaume Flandre
I have dozens of <style> elements in the page, I cant which is the one i previously created.
vsync
Yeah, in that case that wouldn't work
Guillaume Flandre
A: 

Giving it an id should work.

$('head').append('<style id="some-id"> ... </style>');

console.log($('#some-id'));

However, in case you're not aware, there are much easier ways to add and remove styles from a document in jQuery.

Jordan
The link you gave me if for styling each individual element. its not really what I need. image the element doesn't even exist yet. even if it is, its really a lot slower and less safe to put style attribute on each element rather that declare a <style> for them all.
vsync
I see what you mean; feel free to disregard that part of my answer. The solution to your problem is still to make sure your style element is getting assigned an id, make sure it's properly getting added to the DOM, and then accessing it by id.
Jordan