Posts Tagged ‘on-the-fly’

Appending Style Nodes with Javascript

Appending Style Nodes with Javascript

In Javascript it often makes sense to attach a stylesheet rather than style a bunch of individual attributes. Appending a stylesheet to the DOM has a number of advantages:

  • Stylesheets can be easier to work with than Javascript—it’s just more natural to use CSS syntax for styling.
  • It’s nice to avoid the cross-browser headaches associated with Javascript styling. Compare CSS’s simple float: left to Javascript’s style.styleFloat = ‘left’ and style.cssFloat = ‘left’.
  • Appending a stylesheet is better for performance when styling 15 or more elements.
  • CSS allows you to leverage pseudo-classes and define styles with the simple a:hover selector instead of both onmouseover and onmouseout event listeners.

There are a couple ways to append a stylesheet. Although it’s usually best to attach an external stylesheet, there are times when you need to build a stylesheet on the fly with Javascript. Let’s walk through the code we’ll need to append … Read more…