Saturday, July 30, 2011

Dynamically Adding Styles to HTML Pages

I came into a situation where I needed to apply styles to the entire page after the page was loaded. Using techniques like targeting elements by their CSS selectors and applying styles to them with jQuery or similar tools would not be sufficient, because I would have to do it every time elements are added to the DOM and it would have required specifically adding a class (or some other attribute) to each element I wanted to apply the style to.

The solution I ended up implementing was to add styles to the page dynamically using JavaScript. Normal browsers let you manipulate the Head element as any other element, so all I needed to do was to append the Style element as a child of the Head element, and set the style's inner HTML with the CSS content:

function addCustomStyle() {
   var style = document.createElement("style");
   style.innerHTML = ".someclass {color: green;}";
   var head = document.getElementsByTagName("head")[0];
   head.appendChild(style);
}

Unsurprisingly like so many other cases, Internet Explorer has its own way of doing stuff. It doesn't allow manipulating the Head element as other elements, but it does provide an API for adding CSS rules to the document. Here is how it's done:

function addCustomStyle() {
   var style = document.createStyleSheet();
   style.addRule(".someclass", "color: green;");
}

You could wrap the two methods with IE conditional tags ([if !IE] and [if IE]) so only one of them will actually be used depending on the browser, or you can come up with your own mechanism. If you are using GWT, deferred binding is perfect for this.