JavaScript DOM, need help to manually create a CSS style in <head>

Let's say I wanted to create a CSS style within a page that looks like this:

.someStyle {
    background: #FF0000;
}

I'm trying to use JavaScript DOM to create it, and I have something like:

var someStyle= document.createElement('someStyle');
someStyle.type = 'text/css';
someStyle.innerHTML = '.cssClass { color: #FF0000; }';
document.getElementsByTagName('head')[0].appendChild(someStyle);

Open in new window


But it's not working because I'm not seeing anything appear in the page through the webkit browser debugger at all. I need this created so that I can use jQuery's addClass("someStyle") inside my code. I would appreciate any help. Thanks.

P.S. Yes, I need to do it this way, please don't suggest using the .css() method of jQuery, it does not fulfill what I'm trying to do.
elepilAsked:
Who is Participating?
 
Tom BeckCommented:
This code worked in my test, Chrome, Firefox and Safari (don't have IE):
var head = document.head || document.getElementsByTagName('head')[0],
	    style = document.createElement('style'),
	    css = '.cssClass { color: #FF0000; }';
	    style.type = 'text/css';
	if (style.styleSheet){
	  style.styleSheet.cssText = css;
	} else {
	  style.appendChild(document.createTextNode(css));
	}

    head.appendChild(style);

Open in new window

0
 
elepilAuthor Commented:
Works like a charm, Tom! Thanks!

Strange though, when I look at the code through Chrome's webkit, I do not see the newly-created style appearing within the <style> tag at all. To your knowledge, is that the way it really is?
0
 
Tom BeckCommented:
Not on my system. All three browser developer tools show the dynamically created style bock in the DOM. This is chrome. Be sure you are looking at the DOM, not the "view source".
Chrome developer toolsThanks for the points.
0
 
Tom BeckCommented:
If you prefer, you can add the new definition to an existing <style> block if one exists by changing the following line.
style = document.getElementsByTagName('style')[0] || document.createElement('style'),

Open in new window

It will be added to the first <style> block in the head section.
0
 
elepilAuthor Commented:
Ah, I see it now. I was at the Sources tab, I had to switch over to the Elements tab to see the DOM. Thanks again!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.