0

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

encoder
  • 595
  • 6
  • 14
  • 1
    style elements are only applied when in the head of a document. instead of a documentFragment, you would need to create a new document for this. – kennebec Feb 03 '12 at 19:56
  • Thanks to those who replied. The more I research this, the more it seems not worth the effort - not to do something in browsers so old they don't hold much market share anymore. I learned quite a bit, though! Anyway, @kennebec, I had read something that said doc.implementation wasn't available in FF3.0, so I hadn't tried that and dismissed your comment at first - but now I found something else that says it is - so who knows, you're probably right. I would test it if I wasn't tired of testing everything under the sun to make this work. Thx though! – encoder Feb 03 '12 at 23:38

1 Answers1

2

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').

entropid
  • 6,130
  • 5
  • 32
  • 45