Reputation: 4908
I want to let the user tell me how h2 should style text. I know that
$('h2').css({'color':'red'});
will go through and change all the h2 tags to
<h2 style="color: red;">This is the header</h2>
But that doesn't change what a basic
<h2>something</h2>
looks like. If I tell an RTE, for example, to put h2 tags around something, I won't get the red style that jQuery defined (most likely).
Is there a way that jQuery can change the CSS that defines the basic h2, so that the h2 set in by an RTE reflects the new style?
Thanks
Upvotes: 1
Views: 1037
Reputation: 28974
You have to create a style
element and append it to head
, like this:
// array containing our styles
var styles = [
"h2 { color: red; }",
"h3 { color: green; }"
];
// create the style element and concat the styles
$("<style>" + styles.join("") + "</style>").appendTo("head");
Note: You don't have to use the array, I only added it to make it easier to add multiple styles.
You can also insert your rules into the stylesheet with the native .insertRule
method:
// get the last stylesheet
var sheet = document.styleSheets[document.styleSheets.length-1];
// get a reference to the insertRule function
// the addRule method is used in IE8 and older
var insertRule = sheet[sheet.insertRule ? "insertRule" : "addRule"];
// reuse the styles-array from the jQuery snippet
while (styles.length) {
insertRule.call(sheet, styles.splice(0,1));
}
Upvotes: 3
Reputation: 4170
You can use the DOM Level 2 interfaces
sheet.insertRule("h2 {color: red;}", 0);
and for IE:
sheet.addRule("h2","color: red;", 0);
Upvotes: 0