Easier CSS rules through DOM Scripting

In Chapter 9 of the book, I talk about using DOM Scripting to set styles. More importantly, I talk about when to do it:

You can use the DOM to plug the gaps between current and future CSS support.

Dustin Diaz has written up a nice example of doing just that.

Say you want to style form fields. You probably want to apply different styles to your text inputs, your submit buttons, your checkboxes, etc. But they all share the same tag name, input, so you can’t just use an element selector in your CSS.

Ideally, you’d be able to use the attribute selector to target each type of input differently. Unfortunately, the browser support just isn’t there yet (I’m looking at you, IE).

As a workaround, you could add class names for each type of input, class="text", class="checkbox", etc. Doing that by hand would get very tedious very quickly.

That’s where Dustin’s little script comes in. It takes the value from the type attribute and appends to the class name of the input:

function appendInputTypeClasses() {
  if ( !document.getElementsByTagName ) return;
  var inputs = document.getElementsByTagName('input');
  var inputLen = inputs.length;
  for ( i=0; i < inputLen; i++ ) {
    if ( inputs[i].getAttribute('type') ) {
      inputs[i].className += ' '+inputs[i].getAttribute('type');
(I’ve slightly changed the formatting from Dustin’s transcription)

Now you can target those classes in your CSS using the class selector: .text, .checkbox, etc.

It’s a nice little script that you can drop into any website. And once attribute selectors enjoy wider support, you can simply take the script out and use pure CSS instead.

Posted by Jeremy on Friday, December 23rd, 2005 at 11:51pm


Be aware that the example, as given by Dustin, does not work in IE6 — the intended target of the script.

The script is fine. The style rules fail. Reasonably, he combines modern and legacy selectors in one ruleset. IE, however, throws out the entire ruleset when it encounters the unfamiliar attribute selector. They have to be separated as in the example below:

input.checkbox {border:1px dotted red;} input[type=’checkbox’] {outline:1px solid red;}

Note also the IE does not recognize many style properties for input tags anyway — and when it does, it may be the wrong property.

This comment form sucks. Why do I have to type in microscopic font in a microscopic form element? Gawd I hate cramped forms…

# Posted by Brett Merkey on Sunday, December 25th, 2005 at 11:10pm

Wow Brett, you’re an angry guy.

Anyhoo, does anyone know if it’s possible to detect support for particular selectors, like "first-child"?

Hmmmm. Ok, Bye.

# Posted by Dan Dean on Saturday, January 21st, 2006 at 12:37am

Sorry. Comments are closed.

December 2005

Recommended Reading

XML Subscribe

Grab the RSS feed for this blog.

JavaScript API

Grab the RSS feed of comments for this entry.