Easy Input CSS Rules

Posted on by

I ran across a post on the DOM Scripting blog, the other day, and saw a great opportunity to demo the brevity of jQuery, observe:

Old DOM Way:

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');
    }
  }
}

New jQuery Way:

$("input").each(function(){
   $(this).addClass(this.type);
});

I'm even considering implementing a new way of circumventing the each() function, observe:

$("input").addClass("{type}");

You really can't get much shorter than that, when it comes to Javascript code. I have quite a few more "old" DOM scripting examples that I'll be posting/improving in the next couple days.

2 thoughts on “Easy Input CSS Rules

  1. So, I’m impressed and will heavily use the script in my new CMS, unfortunately I always get a debugging error with the new FIREBUG Plugin. I changed your last set Timeout function to
    “if ( typeof Prototype == “defined” && $.g == null && $.clean == null)”, that’s it…
    Nice work…seems to be what I’m looking for since 100 years…

  2. renkert: I’ve resolved the bug, it’s now using

    typeof Prototype != "undefined"

    Unfortunately, there’s no ‘defined’ value. Thanks for the heads-up, though!