I was in need of a very simple function: to append a css class to all form input elements on a page by extracting the input type from the element in question.

In effect, this:

<input type="text" name="name" value="" />
<input type="submit" name="submit" value="Submit" />

becomes this:

<input type="text" name="name" value="" class="text" />
<input type="submit" name="submit" value="Submit" class="submit" />

Until attribute selectors ( input [type=submit] {} ) become the standard, this function will allow me to style my inputs with CSS without having to manually apply classes in my html. The cleaner I can keep my code the happier I am.

attrToClass Source:

Comments and suggestions for improvement would be much appreciated:

jQuery.fn.attrToClass = function(e) {
	$(this).each(
		function(intIndex){
		    $(this).addClass($(this).attr(e));
	});
};
 
$(document).ready(function(){
       // designate the tag and the attribute to be extracted
	$("input").attrToClass("type");
});

Update

After playing with this function for a bit I realized it would be just as easy to pull just about any other attribute, from just about any other tags, and apply the classes. Names, for example, would be just as plausible, and probably more versatile, as class name:

<input type="submit" name="submitContact" value="Submit" />
 
to
 
<input type="submit" name="submitContact" value="Submit" class="submitContact" />

With that said, the function has been updated to allow you to designate the tag and attribute type within the function call. Any further updates/fixes will be at this Gist