1

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

Steve
  • 4,534
  • 9
  • 52
  • 110
  • Possible duplicate: http://stackoverflow.com/questions/1720332/how-to-change-the-inline-style-of-the-page-using-jquery – rossipedia Jul 03 '13 at 18:49

2 Answers2

3

Using jQuery

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.

See test case on jsFiddle.

Using the native CSSStyleSheet.insertRule

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

See test case on jsFiddle.

mekwall
  • 28,614
  • 6
  • 75
  • 77
  • Thanks! The jQuery method seems easiest and I feel more at home with jQuery. Plus your jsfiddle for the insertRule wasn't showing the colors. I was also directed to the jQuery.rules plugin by an earlier post. Do you have any thoughts on that for a solution? – Steve Jul 03 '13 at 19:56
  • @Steve The native method should be preferred though but it's weird it does't work for you. What browser are you using? jQuery.rule is just a plugin that more or less does the same as the snippet in my answer. You can use it if you want, but I think it's unnecessary. – mekwall Jul 03 '13 at 21:08
  • 1
    Marcus, Your http://jsfiddle.net/hA6My/1/ jsfiddle is colorless her on Firefox and IE, but works on Chrome and Safari. No matter. I'm happy with the jQuery solution, which works everywhere. Thanks. – Steve Jul 05 '13 at 21:06
0

You can use the DOM Level 2 interfaces

sheet.insertRule("h2 {color: red;}", 0);

and for IE:

sheet.addRule("h2","color: red;", 0);
stackErr
  • 4,130
  • 3
  • 24
  • 48