encoder
encoder

Reputation: 605

How do I add CSS rules to a document fragment across IE/FF?

I am trying to create and then style a document fragment, but am having quite a bit of difficulty. Ironically, IE is not my problem!

I have this:

var newDom = document.createDocumentFragment();

newDom.appendChild(document.createElement("style"));
newDom.appendChild(document.createElement("div"));

if (newDom.childNodes[0].styleSheet){
    newDom.childNodes[0].styleSheet.cssText = "div{color:red;}";
    alert(newDom.childNodes[1].currentStyle.color);
}else{
    newDom.childNodes[0].appendChild(document.createTextNode("div{color:red;}"));
    alert(window.getComputedStyle(newDom.childNodes[1], null).color);
};

...which alerts "red" in IE7/8/9, but "rgb(0,0,0)" in FF3.0/4/10. And, yes, I will need to know what styles are applied, so I will need to read from getComputedStyle in FF (or use some other method, so long as it's reliable).

What am I doing wrong? Is this possible? (I would think/hope so...)

I've tried lots of things - like "newDom.styleSheets", which exists in IE but not FF - to no avail.

Please help - Thanks! :D

Upvotes: 0

Views: 4297

Answers (1)

entropid
entropid

Reputation: 6239

Reading on the web, it seems that the right syntax to change the CSS using Javascript is:

obj.style.cssText = 'something';

Anyway, this doesn't seem to solve the problem. I would suggest you to read this article, that might help you: http://www.phpied.com/the-new-game-show-will-it-reflow/.

I would also suggest to change the approach and put your CSS code in a pre-existing CSS stylesheet, associated with a class like .red-color, and then just the class to the newly created div, with setAttribute('class', 'red-color'). Another alternative would be to set the style inline, always with the same function: setAttribute('style', 'color: red').

Upvotes: 2

Related Questions