July 3, 2009

Temporary CSS

Given the text of a styleSheet (strCSS), it will apply the styles to the current document.
The next time it’s called, the old styleSheet is replaced by the new text.
In this fashion, you can quickly create conditional styles document-wide.


The function returns the text it was fed, so you can use it in a chain.

function useCSS(strCSS) {
	var D = document, ns, nsx, h = D.getElementsByTagName("head");
	if (!h[0]) {
	  return;
	} else {
	  h = h[0];
	}
	if (!useCSS._css) {
	  ns = D.createElement("style");
	  ns.type = "text/css";
	  h.appendChild(ns);
 	  useCSS._css=ns;
	} else {
	  ns = useCSS._css;
	}
	if (nsx = ns.styleSheet) {
	  return nsx.cssText = strCSS;
	} else {
	  ns.innerHTML = ""; 
	  ns.appendChild(D.createTextNode(strCSS));
	}
	return strCSS;
}