Dave Stein
Dave Stein

Reputation: 9316

How can I change cssText in IE?

In the past I've been able to modify the CSS on a page via an inline style tag. I know this sounds horrible but it's for custom CSS writing while working on a kind of WYSIWYG (not with text though).

I used to do something like: tag.styleSheet.cssText = myrules;

I don't know when exactly, but at some point IE started saying "Invalid Argument" when I try this. The real crux is that doing tag.innerHTML = 'body {}' gives Unable to set value of the property 'innerHTML': object is null or undefined which doesn't happen in any other browser.

EDIT

To be clear I am using an inline style tag. I am not trying to use the inline style attribute.

<style type="text/css" id="mytag"></style>

How can I change the inside of that tag?

EDIT 2 Please see this fiddle:

http://jsfiddle.net/tTr5d/

It appears that my solution of tag.styleSheet.cssText is identical to using styleSheets property. You can comment out the last definition of cssText to see it working as proposed by @Teemu. So now I'm real lost why it's not working in my app. If anyone has ideas what could break that functionality that would be great. In the meantime I'll be tinkering around my app.

Upvotes: 0

Views: 3739

Answers (4)

Dave Stein
Dave Stein

Reputation: 9316

IE is limited to 32 stylesheets. I like to forget that fact apparently, which seems to include inline style tags, on top of <link>.

I changed my sandbox to turn on minification so it would put the files together.

Then my code worked.

So it appears that when you go over the limit and insert via JS, you don't get a real error until you try what I did.

Upvotes: 6

Teemu
Teemu

Reputation: 23396

You can get a reference to a styleSheet object only via styleSheets collection (or imports collection). If you refer direct to the style element, you'll just get a HTML-element. (Check properties in both objects within simple for..in-loop, and see the difference)

This works in all IEs, and results are rendered immediately:

document.styleSheets['mytag'].addRule('BODY', 'background-color:red');

More info in MSDN: styleSheet object

Upvotes: 1

kennebec
kennebec

Reputation: 104770

I never had much luck with style elements and IE's innerHTML. The dom methods are surer, even if you need to branch for IE;

without jquery-

function addNewStyle(str, title){
    var el= document.createElement('style');
    if(title) el.title= title;
    if(el.styleSheet) el.styleSheet.cssText= str;
    else el.appendChild(document.createTextNode(str));
    document.getElementsByTagName('head')[0].appendChild(el);
    return el;
}

Upvotes: 0

sachleen
sachleen

Reputation: 31131

You can use jQuery. If it's the inline style, you can use the .attr() function.

$("#myElement").attr('style')

otherwise, you can see what .css() has to offer. You can use that to get and set various CSS styles.

Other CSS related jQuery methods

Upvotes: 0

Related Questions