Checkboxes, textboxes, radio buttons and submit buttons all share the same HTML tag name <input>. The type attribute is what distinguishes each element from each other. For example:
CSS2 gives us the the ability to create style rules based on attributes of elements. So we could create a rule such as:
input[type='button'] {
border: dashed 2px green;
}
input[type='text'] {
border: solid 2px red;
}
This would apply a dashed green border around all the buttons on a page and a solid red border around all text boxes. Unfortunately....you guessed it....Internet Explorer does not support attribute selectors in CSS. So if we want apply different styles to each type of input, then we either have to create inline styles like
<input type="text" style="border: solid 2px red;" />
or apply a class to each element and then create a corresponding CSS class definition.
<style type="text/css">
.textbox { border: solid 2px red; }
</style>
<input type="text" class="textbox" />
Using inline styles is almost never a good idea, and adding a class attribute on every form element is tedious, so I wanted to figure out a way to make this easy on all of us until the day when Microsoft decides to support CSS more fully.
My idea was to create a JavaScript which would find each <input> element on the page and add a class name corresponding to the type of <input> it is.
View an Example
Here is the Javascript code:
<script type="text/javascript">
function addClassNamesToInputs() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
inputs[i].className = inputs[i].type;
}
}
</script>
And here is the CSS which would go along with it:
<style type="text/css">
body { font-family: sans-serif; font-size: 75%; }
input {
border: solid 2px red;
}
input.radio {
border: none;
}
input.checkbox {
border: none;
width: 30px;
height: 30px;
}
input.submit {
border: solid 2px black;
font-family: monospace;
font-size: 18px;
}
input.reset {
border: solid 2px green;
font-family: Sans-Serif;
font-size: 11px;
font-weight: bold;
}
input.button {
border: solid 2px blue;
font-family: Serif;
font-size: 25px;
}
</style>
If you use the prototype.js library, you would want to use the Element.addClassName() function in the script because, the script above will overwrite any existing class name
<script type="text/javascript">
function addClassNamesToInputs() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
inputs[i].addClassName(inputs[i].type);
}
}
</script>
Labels: css, javascript, workaround