i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Input Element CSS woes are over

Somewhere between January and now, my head has been so far stuck up the DOM, I'm out to figure out every last browser annoyance I've ran into and fix it with javascript.

First off; The problem. I want to style my <input /> elements differently depending whether they are type="text" or type="input" (or "button").

If we all lived in the future of css 3, we could easily do the following...

input[type="text"] {

font:bold 10px/12px verdana,arial,serif;

padding:3px;

}

input[type="button"],input[type="submit"] {

/* you know what to do */

}

Get over it. Use CSS 2.1

Being the "non-browser Elitist" I am (meaning, I'm not going to ignore the fact that 85% of users are browsing with a device that won't understand CSS3), I decided to fix this.

Quick solution

Let's just change our HTML to this.

<input type="text" class="text" value="" />

<input type="button" class="button" value="I am a button" />

<input type="submit" class="button" value="I am a submit" />

Then have the complimenting CSS:

input.text { /* my text css */ }

input.button { /* my button css */ }

Simple enough... but I'm still not satisifed. I'm thinking to myself, What a hassle. Who really wants to append all those classes.

Javascript will do it for you

Need I say more....

function changeInputs()

{

var els = document.getElementsByTagName('input');

var elsLen = els.length;

var i = 0;

for ( i=0;i<elsLen;i++ )

{

if ( els[i].getAttribute('type') )

{

if ( els[i].getAttribute('type') == "text" )

els[i].className = 'text';

else

els[i].className = 'button';

}

}

}

With this, simply keep your CSS as it was with the input.text and input.button, but this time you don't need to write the class names in your HTML. It works out just great.

Oh. And don't forget to attach this function to an onload event handler.

Eg.

window.onload = function() { changeInputs(); }

There ya go.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.