+1  A: 

The <style> tag is only allowed in the <head> of HTML and XHTML, not the <body> or any of its descendants. Web browsers tend to be fairly forgiving of this in the initial parsing of a document, but when changing innerHTML I would expect that the browser would ignore any <style> elements because that type of element is not expected there.

As a workaround, would it be possible to use inline-CSS in your response, that is use the style="" attribute of the HTML elements you're passing?

EDIT: To add the CSS to the <head> would require one of two things:

  • Two round trips to your server:
  • A response that includes both and can be parsed before being inserted

In this case, I would recommend encoding your two parts into a JSON object before sending. Your callback on the AJAX action should split these and attach them to their appropriate locations (style first to avoid screen jitter)

{"style":"\ndiv#ajax7373 a {\n  color:#fff;\n  text-decoration:underline;\n  font-weight:bold;\n  \n}\ndiv#ajax7373 {\n  background-color:#ff1cae;\n  color:#ff6ccf;\n}","object":"\n<div id=\"#ajax7373\">\n\tThere is the contents of your div and a <a href=\"#\">link<\/a>\n<\/div>\n"}

That said, I find it hard to believe that the app favors style/content sepration so strongly and is employing a method where the style must generated by the content. Why not style the whole domain, including the expected return of your AJAX requests? Are the AJAX requested items really going to have enough variance in structure/style to warrant this?

yaauie
Ahh...I didn't not know that.Unfortunately no, I can't use inline style attribs... technically I could put them in there, but for a wide variety of reasons, the CSS is being kept intentionally separate.
Adam Haile
for good reasons... you should mark the lement with relevant classes
annakata
+1  A: 

You're stuck with either inline styles for the generated CSS or you'll have to write tons of class names for all the various styles you need so you can still separate out the styling. Then you could alter the class names via JS.

sanchothefat
you seem down on the class based solution but I believe this to be optimal - the layout (CSS) should have complete control over it's domain, and the markup and behaviour (JS) should indicate where and what this applies to
annakata