Styling input elements based on type without breaking IE6

Imagine that you could style all input types without manually adding a class to each input element. And do it without breaking the design for older browsers like IE6. Here is how…

I've come across a few Javascript libraries that tries to make frontend work easier. Since I began using jQuery (Thanks to Oscar from GMTA) I've discovered a few ways to make life easier.

Usually you would style a text input element something like this in CSS:

input[type=text] { border: 2px dashed #f00; background: #ff0; }

But IE6 doesn't do attribute-selectors. So until the marketshare of IE6 is low enough (and customers stop insisting) we need alternatives. But how?

The immediate replacement

With jQuery you can actually do a query for all input types much like the CSS selector. Doing this together with a little CSS, and you've got a powerful replacement:

<script type="text/javascript">
<style type="text/css">
input.text { border: 2px dashed #f00; background: #ff0; }

The result

And the result is as expected, fully automated:


Other input types?

So what about other input types? I usually just repeat the process, since it's a nice and clean way, so I have the following snipplet in my base.js, which is included on all pages like we do on

$(document).ready(function() {
// * Enable ability to custom style all input elements based on their type
// * The equivalent CSS selectors doesn't work in IE 6 (and 7?)
// .......

The non-jQuery and independent way

But to be honest the most optimal way of doing this would be to create a small script that uses document.getElementsByTagName('input') and matches on the 'type' attribute… So here it is a bit more generic but without the dependency on jQuery:

<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for(var i in inputs) {
inputs[i].className += " " + inputs[i].type;

It's actually a bit faster this way, so one would argue the latter method is better.