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() {
(I’ve slightly changed the formatting from Dustin’s transcription)
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');
}
}
}
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
Comments
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
Sorry. Comments are closed.