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.

2 comments:

  1. We particularly appreciated their 75% BTC sportsbook bonus as much as} $750 (fiat bonuses are $250) which is redeemable with your first sports 온라인 카지노 activities betting wager. One factor is for certain – you’ll find yourself playing in} casino games you’ve never seen before with Bitstarz. They’re continually adding new casino games to their already packed library. Their website works beautifully and presents full gaming compatibility throughout their 156 betting choices; even on older cellular gadgets.

    ReplyDelete
  2. The CNC machine uses these programmed instructions to function mechanically and not using a|with no} bodily operator. Manufacturers accrue a number of} advantages CNC machining via the appliance of CNC machining similar to expense discount, improved velocity, better accuracy, and enhanced productiveness ranges. Plain Milling, Surface Milling, or Slab Milling is when the milling cutter axis is parallel to the surface being milled.

    ReplyDelete