Steve
Steve

Reputation: 4908

How can I use jQuery to change CSS that defines H2?

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

Answers (2)

mekwall
mekwall

Reputation: 28974

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.

Upvotes: 3

stackErr
stackErr

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

Related Questions